I'm encountering an issue with TypeScript regarding my interface MentionItem
. Both the id
and value
properties are supposed to be strings, but TypeScript is flagging them as possibly string | undefined.
Interestingly, manually checking that id
and value
are not undefined resolves the TypeScript error. However, when I attempt to validate for undefined values using
Object.values(dataset).includes(undefined)
, TypeScript continues to show an error message.
I'm puzzled by this TypeScript error and looking for guidance on how to rectify it.
Here's a snippet of my code:
interface MentionItem {
id: string;
value: string;
}
getItemData = (): MentionItem => {
const dataset = (this.mentionList.childNodes[this.itemIndex] as HTMLElement).dataset;
if(Object.values(dataset).includes(undefined)) {
throw new Error("Incomplete dataset")
}
return {
id: dataset.id,
value: dataset.value,
};
};
This is the TypeScript Error message:
Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2322)
I find it perplexing why this triggers an error, considering it should function in the same manner. Please correct me if I am mistaken:
The check that satisfies TypeScript
if(dataset.id === undefined || dataset.value === undefined) {
throw new Error("Incomplete dataset")
}
The check that upsets TypeScript
if(Object.values(dataset).includes(undefined)) {
throw new Error("Incomplete dataset")
}