我想从 Typescript 类型或接口(interface)生成一些 joi 模式对象。在我最初的搜索中,我发现了一些相反的事情(从 joi 模式生成 Typescript 类型/接口(interface)),以及 ts-interface-builder + ts-interface-checker提供了一些基于 Typescript 类型/接口(interface)创建运行时检查器的能力,但仍然缺乏功能支持,并且使用围绕 Prop /方法的类和装饰器来完成此任务。
有什么东西可以生成这样的 joi 模式吗?或者有更成熟的接口(interface)/类型运行时检查替代方案? (在从数据库中提取数据并确保数据库的响应结构正确时很有用)
编辑:我想 this io-ts github issue 上有一个关于此类问题的很好的帖子。 .
最佳答案
我找到了一些令我满意的东西:typescript-is .
- 将您正在使用的 typescript 编译器替换为 ttypescript 。而不是调用
tsc
,调用ttsc
. - 将以下内容添加到
tsconfig.json
:
{
"compilerOptions": {
// Rest of ts config options...
"plugins": [
{
"transform": "typescript-is/lib/transform-inline/transformer"
}
]
}
}
-
$ npm install ttypescript typescript-is
- 现在您可以将以下内容添加到您的代码中:
import { is, assertType } from 'typescript-is'
interface SomeInterfaceOrType {
aString: string
}
// To do a simple boolean check, do the following:
const nonConformingObj = { somethingOutOfLeftField: 42 }
const conforms = is<SomeInterfaceOrType>(nonConformingObj) // false
// Or to get better details on what's wrong, do the following
const anotherNonConformer: unknown = { aString: 1337 }
try {
assertType<SomeInterfaceOrType>(anotherNonConformer)
} catch(error) {
console.log(error.message) // logs: "validation failed at anotherNonConformer.aString: expected a string"
}
在编译时,is<T>()
和assertType<T>()
调用将转换为工作运行时检查。不一定是 JOI 模式,但仍然非常简洁,并且对于我的用例来说绝对足够好。
关于javascript - 从 Typescript 类型/接口(interface)生成 Joi 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60658357/