【发布时间】:2020-08-24 17:05:58
【问题描述】:
正如标题所说,我正在尝试创建一个界面,该界面将包含必填字段,但前提是另一个字段具有特定值。
例如:
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 的值,是否有关键字可以做到这一点?
我做错了吗?
感谢您的帮助!
【问题讨论】:
-
我不相信有一种方法可以在界面中进行您需要的那种确定。似乎创建一种方法来检查对象的属性,并从中确定要使用的接口,这可能是您最好的选择;尽管对于类型安全来说似乎很多。也许进入类型守卫领域的旅程会很有用,它可能会使接口确定代码更具可读性:typescriptlang.org/docs/handbook/advanced-types.html 不管怎样,祝你好运,希望你能找到答案。总有办法……一种或另一种!
-
好吧,我想我现在会坚持我丑陋的解决方案。我仍然希望有人会来告诉我只需使用关键字
hasvalueahah。还是谢谢!
标签: typescript typescript-typings typescript-generics