typescript接口验证作为数据验证器在编译后是否有效?

typescript接口验证作为数据验证器在编译后是否有效?,typescript,validation,Typescript,Validation,我曾经使用schema-inspector进行验证。自从我开始使用TypeScript以来,我能否摆脱模式检查器的验证,并根据数据是否符合TS的接口创建抛出和捕获错误的规则?TypeScript在运行时没有数据构造函数,TS创建的唯一运行时结构是Enum,其他东西只是类型注释,仅在编译期间使用,运行时中不存在任何类型 也就是说,我们可以说TS类型只是关于我们所做的契约/假设的信息,它们在运行时没有得到验证 如果您想拥有值构造函数,那么您需要创建给定类型的适当值的函数,或者您自己创建,或者使用一些

我曾经使用
schema-inspector
进行验证。自从我开始使用TypeScript以来,我能否摆脱模式检查器的验证,并根据数据是否符合TS的接口创建抛出和捕获错误的规则?

TypeScript在运行时没有数据构造函数,TS创建的唯一运行时结构是Enum,其他东西只是类型注释,仅在编译期间使用,运行时中不存在任何类型

也就是说,我们可以说TS类型只是关于我们所做的契约/假设的信息,它们在运行时没有得到验证

如果您想拥有值构造函数,那么您需要创建给定类型的适当值的函数,或者您自己创建,或者使用一些第三方库

下面是自定义类型+值构造函数的示例。这种工具只允许创建与类型假设匹配的有效值:

// type
type SomeType = { field: string }
// value constructor
const createSomeType = (a: any): SomeType => {
  const fieldInside = 'field' in a;
  const stringField = typeof a.field === 'string';

  if (!fieldInside || !stringField) {
    throw TypeError('SomeType value was not able to be created');
  }
  return { field: a.field }; // proper value
}

const someValue = createSomeType({ field: 'someStr' }) // correct no error
createSomeType({ otherField: 'x' }) // exception

TypeScript在运行时中没有数据构造函数,TS创建的唯一运行时结构是Enum,其他东西只是类型注释,仅在编译期间使用,运行时中不存在任何类型

也就是说,我们可以说TS类型只是关于我们所做的契约/假设的信息,它们在运行时没有得到验证

如果您想拥有值构造函数,那么您需要创建给定类型的适当值的函数,或者您自己创建,或者使用一些第三方库

下面是自定义类型+值构造函数的示例。这种工具只允许创建与类型假设匹配的有效值:

// type
type SomeType = { field: string }
// value constructor
const createSomeType = (a: any): SomeType => {
  const fieldInside = 'field' in a;
  const stringField = typeof a.field === 'string';

  if (!fieldInside || !stringField) {
    throw TypeError('SomeType value was not able to be created');
  }
  return { field: a.field }; // proper value
}

const someValue = createSomeType({ field: 'someStr' }) // correct no error
createSomeType({ otherField: 'x' }) // exception

这回答了你的问题吗?这回答了你的问题吗?