- Mastering TypeScript 3
- Nathan Rozentals
- 215字
- 2021-07-02 12:42:42
Inferred typing
TypeScript also uses a technique called inferred typing to determine the nature of a variable. This means that even if we do not specify the type, the compiler will check where the variable has first been used, and then use this type for the remainder of the code block. As an example of this, consider the following TypeScript code:
var inferredString = "this is a string""; var inferredNumber = 1; inferredString = inferredNumber;
We start by declaring a variable named inferredString and assign a string value to it. TypeScript identifies that this variable has been assigned a value of type string and will infer that the inferredString variable is of type string. Any further usage of this variable, therefore, will need to treat it as a string type. Our second variable, inferredNumber, has a number assigned to it. Again, TypeScript is inferring the type of this variable to be of type number.
If we then attempt to assign the inferredString variable (of type string) to the inferredNumber variable (of type number) in the last line of code, TypeScript will generate a familiar error message:
error TS2322: Type 'number' is not assignable to type 'string'
This error is generated because of TypeScript's inferred typing rules.