【发布时间】:2021-07-03 00:01:26
【问题描述】:
我有一堂课RawTemplate
export type TestUnion = 'test1' | 'test2';
export class RawTemplate {
someProperty: Record<TestUnion, Record<string, string>>;
}
然后我创建了扩展 RawTemplate 的新类 Raw
export class Raw extends RawTemplate {
someProperty: {
test1: { name1: 'name'; name2: 'name' };
test2: { name3: 'name' };
};
}
然后我创建一个泛型类型Generic 和一个类型Target
export type Key<T extends RawTemplate> = keyof T['someProperty'][TestUnion];
export type Generic<T extends RawTemplate> = Record<Key<T>, string>;
export type Target = Generic<Raw>;
我想得到 Target 这样的类型:{ name1: string; name2: string; name3: string } 但我得到了
关注类型:{}
如果我这样重写我的类型:
export type Key<T extends RawTemplate> = keyof T['someProperty']['test1'];
export type Generic<T extends RawTemplate> = Record<Key<T>, string>;
export type Target = Generic<Raw>;
我得到了关注Target 类型:{ name1: string; name2: string } 几乎如我所愿。
或者我可以这样重写我的类型:
export type Key<T extends RawTemplate> = keyof T['someProperty']['test1' | 'test2'];
export type Generic<T extends RawTemplate> = Record<Key<T>, string>;
export type Target = Generic<Raw>;
但我得到了关注 Target 再次输入:{}
我发现的唯一可行的案例:
export type Key1<T extends RawTemplate> = keyof T['someProperty']['test1'];
export type Key2<T extends RawTemplate> = keyof T['someProperty']['test2'];
export type Generic<T extends RawTemplate> = Record<Key1<T>, string> | Record<Key2<T>, string>;
export type Target = Generic<Raw>;
如何正确写入类型?我将扩展TestUnion 类型,我不想每次都重写我的Generic 类型。
【问题讨论】:
-
“高级”打字不是一件好事
标签: typescript typescript-typings typescript-generics