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
Item 24: Understand How Context Is Used in Type Inference
Things to Remember
Be aware of how context is used in type inference.
If factoring out a variable introduces a type error, maybe add a type annotation.
If the variable is truly a constant, use a const assertion (as const). But be aware that this may result in errors surfacing at use, rather than definition.
Prefer inlining values where it's practical to reduce the need for type annotations.
Code Samples
functionsetLanguage(language: string){/* ... */}setLanguage('JavaScript');// OKletlanguage='JavaScript';setLanguage(language);// OK
typeLanguage='JavaScript'|'TypeScript'|'Python';functionsetLanguage(language: Language){/* ... */}setLanguage('JavaScript');// OKletlanguage='JavaScript';setLanguage(language);// ~~~~~~~~ Argument of type 'string' is not assignable// to parameter of type 'Language'
// Parameter is a (latitude, longitude) pair.functionpanTo(where: [number,number]){/* ... */}panTo([10,20]);// OKconstloc=[10,20];// ^? const loc: number[]panTo(loc);// ~~~ Argument of type 'number[]' is not assignable to// parameter of type '[number, number]'
constloc=[10,20]asconst;// ^? const loc: readonly [10, 20]panTo(loc);// ~~~ The type 'readonly [10, 20]' is 'readonly'// and cannot be assigned to the mutable type '[number, number]'
constloc=[10,20,30]asconst;// error is really here.panTo(loc);// ~~~ Argument of type 'readonly [10, 20, 30]' is not assignable to// parameter of type 'readonly [number, number]'// Source has 3 element(s) but target allows only 2.
typeLanguage='JavaScript'|'TypeScript'|'Python';interfaceGovernedLanguage{language: Language;organization: string;}functioncomplain(language: GovernedLanguage){/* ... */}complain({language: 'TypeScript',organization: 'Microsoft'});// OKconstts={language: 'TypeScript',organization: 'Microsoft',};complain(ts);// ~~ Argument of type '{ language: string; organization: string; }'// is not assignable to parameter of type 'GovernedLanguage'// Types of property 'language' are incompatible// Type 'string' is not assignable to type 'Language'
constfn=(a,b)=>{// ~ Parameter 'a' implicitly has an 'any' type// ~ Parameter 'b' implicitly has an 'any' typeconsole.log(a+b);}callWithRandomNumbers(fn);