我正在使用中介步骤来创建一个类型,该类型的属性键必须与指定的界面
的键相同// 1. Create Interface
interface IDetail {
name: string;
enabled: boolean;
}
// 2. Create a 'type' that has properties that match the properties of an interface
type DetailType = {
[key in keyof IDetail]: any
}
// 3. Apply the type to an object literal
const control: DetailType = {
name: [],
enabled: []
}
我经常重复这种模式,我想知道是否有办法概括第二步-可能使用泛型?
答案 0 :(得分:1)
好吧,您可以使您的类型通用:
interface IDetail {
name: string;
enabled: boolean;
}
type Generic<T> = { [key in keyof T]: any };
const controlGeneric: Generic<IDetail> = {
name: [],
enabled: []
};
答案 1 :(得分:1)
您可以创建特殊的通用类型:
type WrapMyType<T, V> = { [key in keyof T]: V };
const control: WrapMyType<IDetail, any> = {
name: [],
enabled: [],
};
答案 2 :(得分:-1)
如果您不想丢失类型,可以使用此方法
type DetailType<T> = { [key in keyof T]: T[key] };
const control: DetailType<IDetail> = {
name: [], // must be string
enabled: [] // must be boolean
}