Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  63] [ 1]  / answers: 1 / hits: 5820  / 2 Years ago, fri, july 29, 2022, 12:00:00

I have a method getUniqueId which accepts two kinds of interfaces below, which will return the uniqueId depending which interface type passed:


interface ReadOnlyInfo {
itemId: string;
....
}

interface EditInfo {
formId: number;
....
}

function getUniqueId (info: ReadOnlyInfo | EditInfo) {
if (info instanceof ReadOnlyInfo) {
return info.itemId;
}
return info.formId;
}

I am wondering if this is a good practice to use instanceof here. My concern is that I might have many other methods similar to getUniqueId, which accept "ReadOnlyInfo | EditInfo" type as well, so I have to repeat "ReadOnlyInfo | EditInfo" everywhere.


Instead of doing that, I also tried using type:


type CommonInfo = | ReadOnlyInfo | EditInfo;

so, that I can save some code (just do CommondInfo), like below, but that way, I cannot tell which type CommonInfo is, instanceof no longer works and gives me compiler errors.


function getUniqueId (info: CommonInfo) {
if (info instanceof ReadOnlyInfo) {
return info.itemId;
}
return info.formId;
}

So, I am wondering what would be the best practice to design interface/methods in this scenario. Thanks in advance!


More From » typescript

 Answers
2

Interfaces in Typescript just syntatic sugar for your ide. It is unpossible to check interface types like in other languages. Knowing in C# for example.


But with type guard you can recognize which interface are in use.


interface ReadOnlyInfo {
itemId: string;
....
}

interface EditInfo {
formId: number;
....
}

function getUniqueId (info: ReadOnlyInfo | EditInfo) {
if (isReadOnlyInfo(info)) return info.itemId;
if (isEditInfo(info)) return info.formId;
}

function isReadOnlyInfo(item: any): item is ReadOnlyInfo {
return 'itemId' in item;
}

function isEditInfo(item: any): item is EditInfo {
return 'formId' in item;
}

On this way you get a better ide support


[#49] Monday, July 4, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anais

Total Points: 672
Total Questions: 118
Total Answers: 121

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
anais questions
Mon, Jul 19, 21, 00:00, 3 Years ago
Tue, May 11, 21, 00:00, 3 Years ago
Fri, Apr 2, 21, 00:00, 3 Years ago
;