typescript - 基于Typescript接口(interface)中另一个字段值的条件字段

标签 typescript typescript-typings typescript-generics

正如标题所说,我正在尝试创建一个 接口(interface)这将具有必填字段,但前提是另一个字段具有特定值。

例如 :

const schema = {
    str: { type: 'string' },
    nbr: { type: 'number' },
    bool: { type: 'boolean' },
    date: { type: 'date' },
    strs: { type: ['string'] },
    obj: { type: 'object' },
} as ISchema;

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

我用这段代码成功地做到了:
interface SchemaOptionsObject {
    type: 'object' | ['object'] ;
    properties: ISchema;
}
interface SchemaOptionsString {
    type: 'string' | ['string'] ;
}
interface SchemaOptionsNumber {
    type: 'number' | ['number'] ;
}
interface SchemaOptionsBoolean {
    type: 'boolean' | ['boolean'];
}
interface SchemaOptionsDate {
    type: 'date' | ['date'] ;
}

type SchemaOptions = SchemaOptionsString | SchemaOptionsNumber | SchemaOptionsBoolean | SchemaOptionsDate | SchemaOptionsObject;

export interface ISchema {
    [key: string]: SchemaOptions;
}

但是这个解决方案太重复了。我试图分解它并最终遇到了一个问题:
export type SchemaAllowedTypes = 'string' | 'number' | 'boolean' | 'date' | 'object';

type SchemaOptionsObject<T extends SchemaAllowedTypes> =
    T extends 'object' ?
        { properties: ISchema } :
        {};

type SchemaOptions<T extends SchemaAllowedTypes> = {
    type: T | T[];
} & SchemaOptionsObject<T>;

export interface ISchema {
    [key: string]: SchemaOptions<SchemaAllowedTypes>;
}

我知道它不起作用,因为 T extends 'object'但我不知道如何检查 T 的值,有没有可以做到这一点的关键字?

我这样做是错误的吗?

谢谢你的帮助 !

最佳答案

这个怎么样?

export type SchemaAllowedTypes = 'string' | 'number' | 'boolean' | 'date' | 'object';

interface SchemaOptionsGeneric<T extends SchemaAllowedTypes>{
    type: T | [T] ;
}
interface SchemaOptionsObject extends SchemaOptionsGeneric<"object">{
    properties: ISchema;
}
type SchemaOptions = SchemaOptionsGeneric<"string"|"number"|"boolean"|"date"> | SchemaOptionsObject

export interface ISchema {
    [key: string]: SchemaOptions;
}

关于typescript - 基于Typescript接口(interface)中另一个字段值的条件字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61691049/

相关文章:

typescript - typescript 中的打字是什么

typescript - 如何在 vscode 中全局引用 *.d.ts

typescript - 映射到对象的元组数组不会产生正确的值

javascript - http post 订阅并 try catch

TypeScript:从其他字符串文字联合类型限制区分联合中的鉴别器

javascript - 动态工厂方法 - 通过字符串实例化类收到错误 TS2322 : Type 'Util' is not assignable to type 'void'

typescript - 如果已知数组类型,则保留数组类型

typescript 选择问题

angular - 在 typescript 中使用参数时如何显示所有通知

typescript - 如何获取嵌套对象的类型推断?