n8j*_*ams 11 javascript node.js typescript joi
我想从 Typescript 类型或接口生成一些 joi 模式对象。在我最初的搜索中,我发现了一些相反的事情(从 joi 模式生成 Typescript 类型/接口),并且ts-interface-builder
提供ts-interface-checker
了一些基于 Typescript 类型/接口创建运行时检查器的能力,但仍然缺乏功能支持,并且整个使用围绕道具/方法的类和装饰器来完成此任务的一堆粗糙的东西。
有没有什么东西可以生成这样的 joi 模式?或者有更成熟的接口/类型运行时检查替代方案?(当从数据库中提取并确保来自数据库的响应具有正确的结构时很有用)
编辑:我想在这个io-ts github问题上有一个关于此类问题的很好的帖子。
我找到了令我满意的东西:typescript-is。
tsc
,不如打电话ttsc
。tsconfig.json
:{
"compilerOptions": {
// Rest of ts config options...
"plugins": [
{
"transform": "typescript-is/lib/transform-inline/transformer"
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
$ 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"
}
Run Code Online (Sandbox Code Playgroud)
在编译时,is<T>()
和assertType<T>()
调用将转换为工作运行时检查。不一定是 JOI 模式,但仍然非常简洁,并且对于我的用例来说绝对足够好。
归档时间: |
|
查看次数: |
9335 次 |
最近记录: |