TypeScript 中的内部类类型
在 TypeScript 中有没有办法创建内部类类型?类似这样的东西:
class Example<Data extends Record<string, any>> {
type Key = keyof Data; // not allowed
getKeys(): Key[] { ... }
}
这在函数块中是可能的,例如:
function getKeys<Data extends Record<string, any>>(data: Data) {
type Key = keyof Data; // allowed
const keys: Key[] = Object.keys(data);
return keys
}
最接近的解决方案是定义一个泛型:
class Example<Data extends Record<string, any>, Key = keyof Data> {
getKeys(): Key[] { return [] }
}
const example = new Example<{aKey: 'value'}>();
const example2 = new Example<{aKey: 'value'}, "aKey">();
但是:
- 类型
key可能会被重写(因为我们只给T提供了默认值) - 因为它可以被重写,在某些情况下,如果我假设返回类型是
T而没有显式地进行类型转换,TS会报错。
有没有什么干净的解决方案或变通方法?
答案#1
据我所知,目前这是不可能的:参见 #7061:允许在类内部声明类型别名