![](/img/trans.png)
[英]Define A Typescript Interface Where A Property Is An Existing Object's Properties
[英]TypeScript - Interface. Define a property with either empty object or this object
以这个TypeScript代码为例:
interface IBook {
metadata: {} | {
title: string;
author: string
};
}
const bookOne: IBook = {
metadata: {}
};
const bookTwo: IBook = {
metadata: {
TEST: 'Red Book',
}
};
如您所见, metadata
只能是一个对象。 但是,我想弄清楚的是,我如何使它成为空对象( {}
),或者如果它需要在该对象中具有属性以使其仅为title
和author
。
我想我知道为什么这是错的,但我似乎无法找到。 救命?
如果可以拥有metadata
子集,那么Hitmands的答案就可以了,因为它只允许你拥有author
,只有title
或两者兼而有之。
否则,如果您正在寻找“全有或全无”场景,我会选择使metadata
可选:
interface IBook {
metadata?: {
title: string;
author: string
};
}
这样,您要么拥有完整的metadata
对象,要么没有。
作为替代方案,您可以使metadata
可能undefined
:
interface IBook {
metadata: undefined | {
title: string;
author: string
};
}
但是,即使没有数据,这也会强制分配metadata
数据:
// Error. Property `metadata` is missing but required in type `IBook`.
const bookOne: IBook = {};
// Valid.
const bookTwo: IBook = {
metadata: undefined
};
看起来既不是title
也不是author
都是必需的属性......所以最好将它们标记为optional
imho。
interface IBook {
metadata: {
title?: string;
author?: string;
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.