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
"Unsoundness" is when a symbol's value at runtime diverges from its static type. It can lead to crashes and other bad behavior without type errors.
Be aware of some of the common ways that unsoundness can arise: any types, type assertions (as, is), object and array lookups, and inaccurate type definitions.
Avoid mutating function parameters as this can lead to unsoundness. Mark them as read-only if you don't intend to mutate them.
Make sure child classes match their parent's method declarations.
Be aware of how optional properties can lead to unsound types.
functionlogNumber(x: number){console.log(x.toFixed(1));// x is a string at runtime// ^? (parameter) x: number}constnum: any='forty two';logNumber(num);// no error
functionlogNumber(x: number){console.log(x.toFixed(1));}consthour=(newDate()).getHours()||null;// ^? const hour: number | nulllogNumber(hour);// ~~~~ ... Type 'null' is not assignable to type 'number'.logNumber(hourasnumber);// type checks, but might blow up at runtime
declarefunctionf(): number|string;constf1: ()=>number|string|boolean=f;// OKconstf2: ()=>number=f;// ~~ Type '() => string | number' is not assignable to type '() => number'.// Type 'string | number' is not assignable to type 'number'.
declarefunctionf(x: number|string): void;constf1: (x: number|string|boolean)=>void=f;// ~~// Type 'string | number | boolean' is not assignable to type 'string | number'.constf2: (x: number)=>void=f;// OK
functionaddFoxOrHen(animals: Animal[]){animals.push(Math.random()>0.5 ? newFox() : newHen());}consthenhouse: Hen[]=[newHen()];addFoxOrHen(henhouse);// oh no, a fox in the henhouse!
functionaddFoxOrHen(animals: readonlyAnimal[]){animals.push(Math.random()>0.5 ? newFox() : newHen());// ~~~~ Property 'push' does not exist on type 'readonly Animal[]'.}
functionfoxOrHen(): Animal{returnMath.random()>0.5 ? newFox() : newHen();}consthenhouse: Hen[]=[newHen(),foxOrHen()];// ~~~~~~~~~~ error, yay! Chickens are safe.// Type 'Animal' is missing the following properties from type 'Hen': ...
processFact({fact: 'Peanuts are not actually nuts',author: 'Botanists'},f=>deletef.author);// Type checks, but throws `Cannot read property 'blink' of undefined`.