You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently (3.4) type guards do not work when variable is declared using type variable. Ideally type guard should be applied not only to variable, but also to type variable. More details in sample code below:
interfaceRecordTypes{cat: {name: string};dog: {name: string};person: {firstname: string,lastname: string};}typeKind=keyofRecordTypes;// "cat" | "dog" | "person" functionlogAnimal(kind: "cat"|"dog"){/* */}functionlogAny(kind: Kind){if(kind=="cat"||kind=="dog"){// type guard is applied here, so typescript knows// that typeof kind == "cat" | "dog" in this block// and we can call logAnimal function without errorlogAnimal(kind);// OK}/* */}// But type guards do not work if we use type variablesfunctiongetName<KextendsKind>(kind: K,record: RecordTypes[K]){if(kind=="cat"||kind=="dog"){// type guard is not applied here, so typescript does not know// that typeof kind == "cat" | "dog" in this block// and we get error when calling logAnimal functionlogAnimal(kind);// ERROR!!!// Correct behaviour should be to apply type guard not only// to variable kind, but also to type variable K, so in this block:// K extends "cat" | "dog"// and then typescript will also know that// typeof record == RecordTypes["cat" | "dog"]// and next line will compile withot errorreturnrecord.name;// ERROR!!!}if(kind=="person"){returnrecord.firstname+' '+record.lastname;// ERROR!!!// ^^^ This is actual problem we often ecounter in our project that// for this kind of code we have to add typecasts or create typecasted // variables like:// const person = record as RecordTypes["person"];}}
Search Terms
type guards type variables
The text was updated successfully, but these errors were encountered:
Currently (3.4) type guards do not work when variable is declared using type variable. Ideally type guard should be applied not only to variable, but also to type variable. More details in sample code below:
Search Terms
type guards type variables
The text was updated successfully, but these errors were encountered: