TypeScript provides the type inference.
const b = true;
console.log(typeof b);
// boolean
const n = 3;
console.log(typeof n);
// number
const f = 3.14;
console.log(typeof f);
// number
const s = 'Hello';
console.log(typeof s);
// string
Best Common Type
When a type inference is made from several expressions, the types of those expressions are used to calculate a 'best common type'.
When no best common type is found, the resulting inference is the union array type.
let arr = [0, 1, null];
arr.push('test'); // Error: argument of type 'test' is not assignable to parameter of type 'number | null'.
Contextual Typing
Contextual typing occurs when the type of an expression is implied by its location.
Common cases include arguments to function calls, right-hand sides of assignments, type assertions, members of an object and array literals, and return statements.
The contextual type also acts as a candidate type in the best common type.
const n1 = 7;
const n2 = n1;
console.log(typeof n2);
// number
'Web > JavaScript' 카테고리의 다른 글
[Jest] Testing with Error Return (0) | 2020.12.28 |
---|---|
[React] Get Keyboard Input (TypeScript) (0) | 2020.12.28 |
[TypeScript] Decorators (0) | 2020.10.24 |
[TypeScript] Iterators and Generators (0) | 2020.10.23 |
[TypeScript] Interface (0) | 2020.10.17 |
댓글