2022/05/12 5

Ts: overloading

// overloading type Config = { path: string, state: number } type Push = { (path: string): void, // call signature을 다르게 표현하는 방법 (config: Config): void // Config 타입을 오버로딩 해서 파라미터를 string(path) 하나만 받을 수도 있고 Config타입에 맞게 받을수 있음 } const push: Push = (config) => { if (typeof config === "string") { console.log(config) } else { console.log(config.state) } } type Add = { (a:number, b:number) : number (a..

Ts:세번째 변수

//unknown 변수 // 만약에 api로 값을 받았을때 파라미터의 타입이 뭔지 모를경우 강제시킴 let a : unknown; //let b = a + 1; // Object is of type 'unknown' if(typeof a === "number"){ let b = a + 1 } if(typeof a === "string"){ let b = a.toUpperCase } function hello():void { console.log("hello bro"); } function hello2() { console.log("hello bro"); } //never 타입 -> 절대 리턴을 하지 않은 경우 never 타입사용 function hello3():never { throw new Error(..

Ts:두번째 변수

// readonly는 실행은 가능하되 변수변경 불가 type player = { readonly name:Name, age?:Age } Ex) nico.name = "jung" // error Ex2) const numbers: readonly number[] = [1, 2, 3, 4] numbers.push(1) // error Ex3) //튜플 const player2: readonly [string, number, boolean] = ["nico", 1, true] player2[0] = 1 // error -> 이중검증 (1) 0번째 index의 타입이 맞지않음 (2) readonly로 변경 보호 Ex4) // null, undefined let a : undefined = undefined l..

Ts:변수의 지정 및 재사용

// 타입재사용 가능 type Age = number; // 타입지정 type Name = string; // 타입지정 type player = { name:Name, age?:Age // ?-> optional } //함수 선언식 function playerMaker(name:string) : player { // 리턴타입 지정(:player) => 리턴타입은 위 type player에서의 //타입값을 재사용 return { name } } //함수 표현식도 동일하게 리턴값 지정 const playerMaker = (name:string) : player => ({name}) const nico = playerMaker("nico"); nico.age = 12