Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  72] [ 7]  / answers: 1 / hits: 21251  / 7 Years ago, sat, may 27, 2017, 12:00:00

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.



Example (non functioning):



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';
}
}

More From » typescript

 Answers
14

No there's not. The best thing to do is to create separate interfaces that describe the two different types of data.



For example:



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
}

[#57644] Wednesday, May 24, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabrina

Total Points: 92
Total Questions: 92
Total Answers: 85

Location: Palestine
Member since Thu, Feb 2, 2023
1 Year ago
;