使用Typescript的类型定义强制执行某个值

使用Typescript的类型定义强制执行某个值,typescript,typescript-types,Typescript,Typescript Types,我有一个Car类,它定义了汽车模型的属性 只有3种可能的模型:“ModelT”、“ModelQ”和“ModelX”。因此,我决定定义一种模型类型,例如: type Model = 'ModelT' | 'ModelQ' | 'ModelX'; 汽车构造方法如下: class Car { constructor(model: Model) { this.model = model; } } 还有一个远程服务,返回我应该购买的车型。如果我使用这样的服务,我的代码如下 const

我有一个
Car
类,它定义了汽车
模型的属性

只有3种可能的模型:“ModelT”、“ModelQ”和“ModelX”。因此,我决定定义一种模型类型,例如:

type Model = 'ModelT' | 'ModelQ' | 'ModelX';
汽车构造方法如下:

class Car {
  constructor(model: Model) {
    this.model = model;
  }
}
还有一个远程服务,返回我应该购买的车型。如果我使用这样的服务,我的代码如下

const model = getModelFromRemoteService();
const car = new Car(model);

在运行时执行逻辑检查远程服务返回的模型实际上是
类型模型定义中指定的模型之一的最佳方法是什么?

不可能从类型/接口开始并从中获取运行时行为。TypeScript中的类型系统仅在您编写程序时存在。它来自在运行时执行的已发出JavaScript

幸运的是,您可以做相反的事情:从运行时存在的对象开始,让TypeScript编译器为它推断类似的类型。在您的情况下,我建议从要检查的值数组开始,然后按照以下说明进行操作:

现在你可以这样使用它:

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
好的,希望能有帮助。祝你好运

可能的重复可能的重复
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