小编Gal*_*anM的帖子

基于 Typescript 接口中另一个字段值的条件字段

正如标题所说,我正在尝试创建一个界面具有必填字段的

例如 :

const schema = {
    str: { type: 'string' },
    nbr: { type: 'number' },
    bool: { type: 'boolean' },
    date: { type: 'date' },
    strs: { type: ['string'] },
    obj: { type: 'object' },
} as ISchema;
Run Code Online (Sandbox Code Playgroud)

我希望这段代码告诉我该字段obj缺少一个属性,因为 的type值为'object'

我用这段代码成功地做到了这一点:

interface SchemaOptionsObject {
    type: 'object' | ['object'] ;
    properties: ISchema;
}
interface SchemaOptionsString {
    type: 'string' | ['string'] ;
}
interface SchemaOptionsNumber {
    type: 'number' | ['number'] ;
} …
Run Code Online (Sandbox Code Playgroud)

typescript typescript-generics typescript-typings

7
推荐指数
1
解决办法
3383
查看次数