打字稿:将对象[名称:类型]转换为接口
Typescript: Transform object [name: Type] to interface
我要转换对象:
var user = {
id: Number,
name: String
}
到界面:
type User = {
id: number
name: string
}
现在我尝试这样做:
type Transform<T extends { [key: string]: ObjectConstructor }> = {[P in keyof T]: (T)[P]['prototype']}
type User = Cast<typeof user>
请帮帮我
您似乎在尝试探查 typeof Number
和 typeof String
的构造:为此,您将使用 construct signature 之类的 new (...args: any) => any
而不是特别是像 ObjectConstructor
这样的构造函数类型。类型 ObjectConstructor
具体是 typeof Object
,并且具有 Object
的所有静态方法,如 Object.keys()
和 Object.values()
,其中 typeof Number
和 typeof String
没有。
但即使你修复了它也不会给你你想要的。当您处理出现的 Number
and String
values as constructors and call new Number()
or new String()
, the InstanceType
时,将是对象类型 Number
和 String
而不是原始类型 number
或 string
。我假设你想要那些原始类型。
在JavaScript中,primitive wrappers also can be used like plain functions (Number()
or String()
without new
) which return primitives instead of objects. So for the case shown here, I'd probe the call signatures like (...args: any) => any)
instead of the construct signatures, and get the ReturnType
的构造函数代替了实例类型:
type Transform<T extends Record<keyof T, (...args: any) => any>> = {
[P in keyof T]: ReturnType<T[P]>
};
type User = Transform<typeof user>
/* type User = {
id: number;
name: string;
} */
我要转换对象:
var user = {
id: Number,
name: String
}
到界面:
type User = {
id: number
name: string
}
现在我尝试这样做:
type Transform<T extends { [key: string]: ObjectConstructor }> = {[P in keyof T]: (T)[P]['prototype']}
type User = Cast<typeof user>
请帮帮我
您似乎在尝试探查 typeof Number
和 typeof String
的构造:为此,您将使用 construct signature 之类的 new (...args: any) => any
而不是特别是像 ObjectConstructor
这样的构造函数类型。类型 ObjectConstructor
具体是 typeof Object
,并且具有 Object
的所有静态方法,如 Object.keys()
和 Object.values()
,其中 typeof Number
和 typeof String
没有。
但即使你修复了它也不会给你你想要的。当您处理出现的 Number
and String
values as constructors and call new Number()
or new String()
, the InstanceType
时,将是对象类型 Number
和 String
而不是原始类型 number
或 string
。我假设你想要那些原始类型。
在JavaScript中,primitive wrappers also can be used like plain functions (Number()
or String()
without new
) which return primitives instead of objects. So for the case shown here, I'd probe the call signatures like (...args: any) => any)
instead of the construct signatures, and get the ReturnType
的构造函数代替了实例类型:
type Transform<T extends Record<keyof T, (...args: any) => any>> = {
[P in keyof T]: ReturnType<T[P]>
};
type User = Transform<typeof user>
/* type User = {
id: number;
name: string;
} */