Typescript 有条件地适用?每个属性的映射类型中的修饰符
从TypeScript文档:Typescript 有条件地适用?每个属性的映射类型中的修饰符,typescript,modifier,mapped-types,Typescript,Modifier,Mapped Types,从TypeScript文档: // Removes 'optional' attributes from a type's properties type Concrete<Type> = { [Property in keyof Type]-?: Type[Property]; }; type MaybeUser = { id: string; name?: string; age?: number; }; 相关GitHub问题: 提取类型中不匹配的道具,我们称
// Removes 'optional' attributes from a type's properties
type Concrete<Type> = {
[Property in keyof Type]-?: Type[Property];
};
type MaybeUser = {
id: string;
name?: string;
age?: number;
};
相关GitHub问题:
NonMatching
matching
扩展推断
技术将两种类型相交type TestType={
a:接口;
b:弦;
};
类型交集您以字符串文字类型并集的形式获得匹配属性这是否回答了您的问题?我原以为没有,但读得好一点也许是这样。有点像,但不是完全
// Not valid TypeScript
type Optionalize<T> = {
[P in keyof T](?: T[P] extends SomeInterface): T[P];
}
type TestType = {
a: SomeInterface;
b: string;
};
type Intersection<A, B> = A & B extends infer U
? { [P in keyof U]: U[P] }
: never;
type Matching<T, SomeInterface> = {
[K in keyof T]: T[K] extends SomeInterface ? K : never;
}[keyof T];
type NonMatching<T, SomeInterface> = {
[K in keyof T]: T[K] extends SomeInterface ? never : K;
}[keyof T];
type DesiredOutcome = Intersection<
Partial<Pick<TestType, Matching<TestType, SomeInterface>>>,
Required<Pick<TestType, NonMatching<TestType, SomeInterface>>
>