使用 TypeScript 接口进行运行时验证 in/of JS 代码

Use TypeScript interface for runtime validation in/of JS code

我可以像这样创建一个 TypeScript 接口,这将有助于静态类型化:

interface IFoo {
   bar: string,
   baz: boolean
}

但我想知道是否有办法将这些信息转换为 JS 并使用它来进行 runtime 验证?否则我可能不得不在两个不同的地方跟踪此信息,这很不好玩。

有人知道这是否可行吗?

它可能看起来像

const ifoo = {
     bar: 'String',
     baz: 'Boolean'
}

然后我可以使用类似的对象来进行运行时验证。

是的!模块 ts-interface-builder 自动将 TypeScript 文件中定义的接口转换为类似于您建议的描述符,即:

import * as t from "ts-interface-checker";
export const IFoo = t.iface([], {
  "bar": "string",
  "baz": "boolean",
});

它与 ts-interface-checker(作为单独的 npm 模块分发)结合使用,后者使用这些描述符通过信息性错误消息进行运行时验证。