본문 바로가기
  • [성공하는 개발자] - Developer

Node/TypeScript8

09. Inference 타입추론 Type Inference (타입추론) function print(message) { console.log(message); } message 아래 ... 추론된 것을 볼 수 있다 에러는 아니지면 경고이다 위처럼 작성하면 어떤 값이든 할당 가능하다 기본 값으로 any 할당 되어 있다 function print(message = 'hello') { console.log(message); } 정확히 타입을 정확하게 지정해줘야 한다. 아니면 message 기본값을 할당 해줘야 한다. function add(x: number, y: number) { return x + y; } const result = add(1, 2); return x + y; 값이 추론 된 것을 볼 수 있다 function add(x: n.. 2021. 4. 20.
8.Intersection Intersection Types: & type Student = { name: string; score: number; }; type Worker = { empolyeeId: number; work: () => void; }; function internWork(person: Student & Worker) { console.log(person.name, person.empolyeeId, person.work()); } internWork({ name: 'sein', score: 1, empolyeeId: 123, work: () => {}, }); 모든것 And 와 비슷하다 Student & Worker 학생이면서 일을 하는 타입 함수를 사용 할 때는 모든 타입에 들어있는 키들을 모두 지정해줘야 한다.. 2021. 4. 17.
7.Union Union Types: OR type Direction = 'left' | 'right' | 'up' | 'down'; function move(direction: Direction) { console.log(direction); } move('down'); type TileSize = 2 | 16 | 32; const tile: TileSize = 16; | or union type 타입으로 설정된 값이 left, right, up, down 으로 정의 되어 있다 move() 입력할시 4가지만 할당 할수 있게 된다 type TileSize 정의 함수는 정의된 숫자만 할당 가능하다 그렇치 않으면 오류 생김 Discriminated union type SuccessState = { result: 'succ.. 2021. 4. 17.
6.Aliases TypeScript 강한 이유는 Aliases 있어서 이다 Type Aliases type Text = string; const name: Text = 'sein'; const address: Text = 'korea'; type Num = number; type Student = { name: string; age: number; }; const student: Student = { name: 'sein', age: 12, }; 직접 원하는 타입을 정의 할수 있으며 새로운 타입을 정의 할 수 있다 type으로 Text 라는 string이라는 타입을 만들 수 있다 String Literal Types type Name = 'name'; let seinName: Name; seinName = 'name';.. 2021. 4. 15.