我有一个这样的代码:
import { ApolloClient } from '@apollo/client';
type F = typeof FeaturesManager.features.warrants
export class FeaturesManager {
static features = {
warrants: Symbol('WARRANTS'),
};
client: ApolloClient<{}>;
constructor({ client }: { client: ApolloClient<{}> }) {
this.client = client;
}
getFeatureAvailability(feature: F) {
}
}
new FeaturesManager(new ApolloClient()).getFeatureAvailability(FeaturesManager.features.warrants)
现在当我改变FeaturesManager.features
时,我也需要改变F
。如何修复这个代码?
Playgroung
要添加所有特性,可以使用keyof
迭代器提取所有键并使用它们对类型进行索引。
type F = typeof FeaturesManager.features[keyof typeof FeaturesManager.features]
或者更简洁的写法是
type ValueOf<T> = T[keyof T];
type F = ValueOf<typeof FeaturesManager.features>
我注意到的另一件事是,你使用的符号可能不是最好的,因为打字稿可能无法识别差异。对于特性,最好使用枚举或字符串,这样你会得到更好的typescript支持。