正如标题所说,我正在尝试创建一个 接口(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/