给定一种包含所有可能性的类型(例如,无标记的联合):
type Input = {
a: string,
b: number,
c: boolean,
};我想用这种API映射它:
type MapItSomehow<T> = ???;
type Output = MapItSomehow<Input>;最终得到这个:
type Output = {
a: string,
b: undefined,
c: undefined,
} | {
a: undefined,
b: number,
c: undefined,
} | {
a: undefined,
b: undefined,
c: boolean,
};证明这是可行的,如果我能做到:
let r: Result = ([] as Result[])[0];
if ('a' in r) {
r.a.trim() // not r.a!.trim()
}
else if // same for each field ...发布于 2021-12-14 14:05:24
type Input = {
a: string,
b: number,
c: boolean,
};
type Values<T> = T[keyof T]
type Mapped<T> = Values<{
[Prop in keyof T]: Record<Prop, T[Prop]>
}>
type Result = Mapped<Input>
declare let x: Result
if ('a' in x) {
x.a.trim()
}Mapped -遍历每个属性并创建预期联合类型的新部分,其中设置当前键,而其他键Exclude<keyof T, Prop>是undefined。
Values -获得所有对象值的联合类型。
https://stackoverflow.com/questions/70350122
复制相似问题