interfaceLib{name:stringadd():string[x:number]:number}typeIsString<T>=Textendsstring?T:never// 컨디셔널 타입, 조건부 타입typeMyLib<T>=Pick<T,IsString<keyofT>>// 분산 조건부 타입typeTest2=IsString<2>typeTest3=IsString<"hi"|2|"hello"|3>typeTest=MyLib<Lib>
선언된 타입과 좁혀진(narrowed) 타입의 이해
functionfoo(x:string|number){if(typeofx==="string"){// x'의 타입은 string타입으로 좁혀졌습니다. 따라서 .length가 가능합니다.console.log(x.length)// 할당을 하게되면 좁혀진 타입이 아닌 선언한 타입이 됩니다.x=1// console.log(x.length); // x는 지금 number 타입이므로 불가능합니다.}else{}}
Leave a comment