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 40: Prefer Imprecise Types to Inaccurate Types
Things to Remember
Avoid the uncanny valley of type safety: complex but inaccurate types are often worse than simpler, less precise types. If you cannot model a type accurately, do not model it inaccurately! Acknowledge the gaps using any or unknown.
Pay attention to error messages and autocomplete as you make typings increasingly precise. It's not just about correctness: developer experience matters, too.
As your types grow more complex, your test suite for them should expand.
Code Samples
interfacePoint{type: 'Point';coordinates: number[];}interfaceLineString{type: 'LineString';coordinates: number[][];}interfacePolygon{type: 'Polygon';coordinates: number[][][];}typeGeometry=Point|LineString|Polygon;// Also several others
constokExpressions: Expression2[]=[10,"red",["+",10,5],["rgb",255,128,64],["case",[">",20,10],"red","blue"],];constinvalidExpressions: Expression2[]=[true,// ~~~ Type 'boolean' is not assignable to type 'Expression2'["**",2,31],// Should be an error: no "**" function["rgb",255,0,127,0],// Should be an error: too many values["case",[">",20,10],"red","blue","green"],// (Too many values)];
typeFnName='+'|'-'|'*'|'/'|'>'|'<'|'case'|'rgb';typeCallExpression=[FnName, ...any[]];typeExpression3=number|string|CallExpression;constokExpressions: Expression3[]=[10,"red",["+",10,5],["rgb",255,128,64],["case",[">",20,10],"red","blue"],];constinvalidExpressions: Expression3[]=[true,// Error: Type 'boolean' is not assignable to type 'Expression3'["**",2,31],// ~~ Type '"**"' is not assignable to type 'FnName'["rgb",255,0,127,0],// Should be an error: too many values["case",[">",20,10],"red","blue","green"],// (Too many values)];
constokExpressions: Expression4[]=[10,"red",["+",10,5],["rgb",255,128,64],["case",[">",20,10],"red","blue"],];constinvalidExpressions: Expression4[]=[true,// ~~~ Type 'boolean' is not assignable to type 'Expression4'["**",2,31],// ~~~~ Type '"**"' is not assignable to type '"+" | "-" | "/" | ...["rgb",255,0,127,0],// ~ Type 'number' is not assignable to type 'undefined'.["case",[">",20,10],"red","blue","green"],// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Types of property 'length' are incompatible.// Type '5' is not assignable to type '4 | 6 | 8 | 10 | 12 | 14 | 16'.];
constmoreOkExpressions: Expression4[]=[['-',12],// ~~~~~~ Type '["-", number]' is not assignable to type 'MathCall'.// Source has 2 element(s) but target requires 3.['+',1,2,3],// ~ Type 'number' is not assignable to type 'undefined'.['*',2,3,4],// ~ Type 'number' is not assignable to type 'undefined'.];