Javascript条件内部TypeScript接口 [英] Javascript Conditional Inside TypeScript Interface
本文介绍了Javascript条件内部TypeScript接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在TypeScript中的接口声明中包含条件。我正在寻找的是一种方式,根据第一个键的值,第二个键可以是这些值。
Is it possible to have a condition inside of an interface declaration in TypeScript. What I'm looking for is a way to say, based on the value of the first key, the second key can be these values.
示例(不起作用):
interface getSublistValue {
/** The internal ID of the sublist. */
sublistId: 'item' | 'partners';
/** The internal ID of a sublist field. */
if (this.sublistId === 'item') {
fieldId: 'itemname' | 'quantity';
}
if (this.sublistId === 'partners') {
fieldId: 'partnername' | 'location';
}
}
推荐答案
否没有。最好的办法是创建描述两种不同类型数据的独立接口。
No there's not. The best thing to do is to create separate interfaces that describe the two different types of data.
例如:
interface SublistItem {
sublistId: 'item';
fieldId: 'itemname' | 'quantity';
}
interface SublistPartners {
sublistId: 'partners';
fieldId: 'partnername' | 'location';
}
function getData(): SublistItem | SublistPartners {
return (Math.random() < 0.5)
? { sublistId: 'item', fieldId: 'itemname' }
: { sublistId: 'partners', fieldId: 'partnername' };
}
const someValue = getData();
if (someValue.sublistId === "item") {
// SublistItem in here
}
else {
// SublistPartners in here
}
这篇关于Javascript条件内部TypeScript接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文