TypeScript
Types
WebDevLee
2023. 5. 4. 13:57
TypeScript에 대한 기본 개념 및 문법에 대해 정리하였습니다.
< From JavaScript to TypeScript >
JavaScript was designed to be very flexible and easy to use for small applications. These features make JavaScript a great first language to learn, but they also make it less-than-ideal for building larger-scale applications with hundreds or even thousands of files.
To address these shortcomings, Microsoft developed TypeScript and released publicly in 2012 to blend the flexibility of JavaScript with the advantages of a stricter language.
< What is TypeScript? >
TypeScript code is a superset of JavaScript code—it has all the features of traditional JavaScript but adds some new features.
< How to use TypeScript >
First, wrte TypeScript code in files with the extension .ts
Second, run the code through the TypeScript transpiler.
: The transpiler will check that the code adheres to TypeScript's standards, and it will display errors
when it does not.
: with this, we can find error before running time.
Third, if the TypeScript code can be converted into working JavaScript, the transpiler will output a JavaScript version of the file (.js)
< Type Inferences >
When we declare a variable with an initial value, the variable can never be reassigned a value of a different data type.
5 primitive data types:
- boolean
- number
- null
- string
- undefined
Example)
let order = 'first';
order = 1;
// Error: Type '1' is not assignable to type 'string'
< Type Shapes >
Because TypeScript knows what types our objets are, it also knows what shapes our objects adhere to. An object's shape describes what properties and methods it does or doesn't contain.
Example)
"OH".length; // 2
"MY".toLowerCase(); // "my"
"MY".toLowercase();
// Property 'toLowercase' does not exist on type '"MY"'.
// Did you mean 'toLowerCase'?
< Any >
When a variable is declared without being assigned an initial value, TypeScript will not try to infer what type the variable is.
: TypeScript will consider a variable to be of type any.
Example)
let onOrOff;
onOrOff = 1;
onOrOff = false;
< Variable Type Annotations >
To declare a variable without an initial value while still ensuring that it will only ever be assigned values of a certain type.
We can tell TypeScript what type something is or will be by using a type annotation(type declaration).
They get automatically removed when compiled to JavaScript.
Example)
let mustBeAString : string;
mustBeAString = 'Catdog';
mustBeAString = 1337;
// Error: Type 'number' is not assignable to type 'string'