因此,您可以这样声明一个通用索引签名:
type GenericType<A> = { firstField: A, secondField: any };
type GenericIndex<T extends object> = {
[K in keyof T]: GenericType<T[K]>;
};
但是在字段级别上可以有通用名称吗?
请参见以下示例中的<R>
:
type GenericType<A, R> = { firstField: A, secondField: R };
type GenericIndex<T extends object> = {
// this line is not compiling because "<R>" is no valid ts syntax here
[K in keyof T]<R>: GenericType<T[K], R>;
};
用法示例:
type SomeType = { a: number, b: string }
const generic: GenericIndex<SomeType> = {
a: { firstField: 1, secondField: "anyString"},
b: { firstField: "someString", secondField: 2}
}
generic.a.secondField // type should be string but is any
generic.b.secondField // type should be numer but is any
请不要以身作则。也可能更复杂。