不可能从类型/接口开始并从中获取运行时行为。 TypeScript 中的类型系统仅在您编写程序时存在。它是在运行时执行的发出的 JavaScript 中的completely erased。
幸运的是,您可以做相反的事情:从运行时存在的对象开始,然后让 TypeScript 编译器为其推断出类似的类型。在您的情况下,我建议从您要检查的值数组开始,然后按照here 所述进行操作:
// helper function needed before TS3.4 to get a tuple of string literals
// instead of just string[]
const stringTuple = <T extends string[]>(...args: T) => args;
const models = stringTuple('ModelT', 'ModelQ', 'ModelX');
// inferred type of models is ['ModelT', 'ModelQ', 'ModelX'];
// in TS3.4+, const models = ['ModelT', 'ModelQ', 'ModelX'] as const;
type Model = typeof models[number];
// inferred type of Model is 'ModelT' | 'ModelQ' | 'ModelX'
现在您再次输入了 Model,并且您还拥有了可用于为其创建 type guard 的 models 数组值:
function isModel(x: any): x is Model {
return models.indexOf(x) >= 0;
// or return models.includes(x) for ES2016+
}
现在你可以像这样使用它了:
class Car {
model: Model;
constructor(model: Model) {
this.model = model;
}
}
// assume this returns a string
declare function getModelFromRemoteService(): string;
// wrap getModelFromRemoteService so that it returns a Model
// or throws a runtime error
function ensureModelFromRemoteService(): Model {
const model = getModelFromRemoteService();
if (isModel(model)) return model;
throw new Error("THAT REMOTE SERVICE LIED TO ME");
}
const model = ensureModelFromRemoteService();
const car = new Car(model); // works now
好的,希望对您有所帮助。祝你好运!