-
The TypeScript Handbook 1์นดํ ๊ณ ๋ฆฌ ์์ 2023. 5. 12. 02:11
What is Typescript
A static Type Checker.
Getting started
1. install
npm install -g typescript
2. compiler
tsc hello.ts;
Types
The primitives : string, number, boolean
Arrays
const number[]; //=== Array<number> const string[];//=== Array<string>
any
type checking์ ํ์ง ์๊ณ ์๋ฐ์คํฌ๋ฆฝํธ์ฒ๋ผ ๋์์ํค๊ณ ์ถ์ ๋
let obj:any = { x:0 };
Type Annotations on Variables
const, var, let ํค์๋๋ก ๋ณ์๋ฅผ ์ ์ํ ๋
let variableName : type = "";
functions
Parameter Type Annotations
function greet(name:string){ console.log(name); }
Return Type Annotaions
function getFavoriteNumber():number{ return 26; }
Anonymous Functions
Object Types
function example(obj: { x:number, y:number}){ }
Optional Properties : add a ?after the property name
function example(obj: { x:number, y?:number}){ }
Union Types
Defining a Union Type
let id : number | string = 2;
Type Aliases
ํ์ ์ ์ ์ํด๋๊ณ ๊ฐ์ ธ๋ค ์ฌ์ฉํ ์ ์๋ค
type TypeName = { x : number; y : number; } function printCoord(pt:TypeName){ }
type ID = number | string; let id : ID = 1;
Interfaces
object type์ ๋ค๋ฅธ ์ด๋ฆ์ด๋ค.
interface Point{ x : number; y : number; }
Differences Between Type Aliases and Interfaces
1. ์์ ๋ฐฉ์
interface Animal{ name : string } interface Bear extends Animal{ honey : boolean; }
type Animal = { name : string; } type Bear = Animal & { honey : boolean; }
2. type ๋ฐฉ์์ ํ ๋ฒ ์ ์๋๋ฉด ๋ณ๊ฒฝํ์ง ๋ชปํ๋ค.
interface Window{ title : stirng; } interface:window{ title : number; }
type Window{ title : stirng; } type:window{ title : number; } //Error : Duplicate identifier
Type Assertions
ํ์ ์คํฌ๋ฆฝํธ๊ฐ ๋ชจ๋ฅด๋ ํ์ ์ ์ฌ์ฉํ ๋
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
.tsx ํ์ผ์์ ๋ค์๊ณผ ๊ฐ์ด ๋ณ๊ฒฝ
const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");
ํ์ ์คํฌ๋ฆฝํธ ์ฌ์ฉ๋ฒ
- ํ์ ์ ๋ชจ๋ ์ ์ํด์ค๋ค. ์ต๋ํ any ํ์ ์ฌ์ฉ x
let name:string = "sinyoung";
๊ทธ๋ฌ๋ ์์ ๊ฐ์ด ๋ณ์ ์ ์ธ๊ณผ ๊ฐ์ ๊ฐ์ด ์ ์ธํ๋ ๊ฒฝ์ฐ์๋ ๋ฐ๋ก ํ ํ์๊ฐ ์๋ค. => ์๋์ผ๋ก ๋ค์ด๊ฐ ๊ฐ์ ํ์ ์ผ๋ก ์ธํ ๋จ.
Types
1. number
2. string
3. boolean
4. null
5. undefined
6. void
7. object
8. array
9. tuples
10..
11. any
12. never
13. unknown