例如,给定一个对象:
const TypeDef1 = {
foo: {optional: true, type: 'string'},
bar: {type: 'number'}
}
符合类型,比如说
type TypeDef = {
[key: string]: {
optional?: boolean,
type: 'number' | 'string' | 'boolean'
}
}
我想要一些可重复使用的打字 Transform<T extends TypeDef>
这样
Transform<typeof TypeDef1>
给出:
{
foo?: string
bar: number
}
这在 Typescript 中可能吗?
最佳答案
您可以使用映射类型和条件类型的组合将类型定义转换为实际类型(前提是我们还在定义上使用 as const
断言以确保保留所有类型信息。
type TypeDef = { [key: string]: { optional?: boolean, type: 'number' | 'string' | 'boolean' } };
type TypeNameToType = {
number: number,
string: string,
boolean: boolean
}
type TypeDefToType<T extends TypeDef> = {
// The optional properties
-readonly [P in keyof T as T[P]['optional'] extends true ? P: never]?: TypeNameToType[T[P]['type']]
} & {
// The mandatory properties
-readonly [P in keyof T as T[P]['optional'] extends true ? never: P]: TypeNameToType[T[P]['type']]
}
const TypeDef1 = {
foo: {optional: true, type: 'string'},
bar: {type: 'number'}
} as const
type X = TypeDefToType<typeof TypeDef1>
// ^?
// type X = {
// foo?: string | undefined;
// } & {
// bar: number;
// }
关于typescript - 在 typescript 中我可以映射一个类型来拥有吗?当属性的相应值满足某个条件时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71291628/