⬅️ FEM TypeScript Fundamentals
Exhaustiveness checking
- Exhaustive” means “considering all possibilities”
function getName(hasName: User | Cat | Dog, names: string[]): true {
switch (hasName.kind) {
case 'user':
names.push(hasName.userName);
return true;
// OR
//case 'user':
//return hasName.userName;
case 'cat':
names.push(hasName.catName);
return true;
case 'dog':
names.push(hasName.dogName);
return true;
}
}
const names: string[] = [];
getName({kind: 'user', userName: 'Amir'}, names);
getName({kind: 'cat', catName: 'Ms. Fluff'}, names);
getName({kind: 'dog', dogName: 'Woofy'}, names);
names;
//Result:
['Amir', 'Ms. Fluff', 'Woofy']- The
truevalue isn’t useful to us at runtime, but we have to return something in order to use exhaustiveness checking. - Generally, we associate exhaustiveness checking with
switch. However, it works withifas well. - In TypeScript, providing a
default:inside of ourswitcheffectively disables exhaustiveness checking.
So in summary when using switch:
- Put the
switchinside of a function where each casereturns. - Give the function an explicit return type.
- Don’t add a
defaultunless you’re very sure that you need one.