본문 바로가기
반응형

개발/TypeScript23

typeof로 object를 구분할 수 없을때 narrowing 하는 방법 : IN 연산자 다음과 같은 경우에는 어떤 에러가 뜰까?? type Korea = { 독도: string }; type Japan = { 후지산: string }; function nationFunction(nation: Korea | Japan) { console.log(nation.독도); } nationFunction({ 독도: "는 우리땅" }); Japan에 '독도' 속성이 없기 때문에, 에러가 발생한다. 이를 해결하기 위해 narrowing을 해야 하는데, typeof의 결과는 number, string, object, array 등이다. Korea, Japan은 typeof에 해당하지 않는다. 그렇다면 어떻게 해야할까?? Korea와 Japan에 공통되지 않는 속성을 골라서 in을 사용한다. 다음과 같은 결.. 2022. 1. 19.
타입스크립트 : rest파라미터의 타입 rest파라미터 함수의 파라미터의 개수가 가변적일때(백만개여도 상관없음), rest 파라미터를 사용할 수 있다. rest파라미터를 사용하면 파라미터를 배열의 형태로 받게 된다. function restParameterFunc(...rest:number[]){ console.log(rest) } restParameterFunc(1,2,3,4,5,6,7,8,9,10) rest파라미터는 파라미터를 배열로 받기 때문에, 타입도 배열이다. 위에서 number형으로 작성했지만, 타입은 배열이다. 2022. 1. 18.
Type alias와 interface 차이 중복되는 타입을 재사용하고 싶을 때 아래코드에서 People 타입과 Creature 타입의 species, age 속성이 중복되는것을 볼 수 있다. interface People { species: string; age: number; } interface Creature { species: string; age: number; numOfFoot: number; //발의 개수 } let june: People = { species: "human", age: 28 }; let 돌돌이: Creature = { species: "dog", age: 3, numOfFoot: 4 }; inferface로 작성하는 경우 위코드에서 species와 age가 겹친다. 그래서 이를 extends를 사용하여 재사용 할 수.. 2022. 1. 15.
타입스크립트에서 DOM 사용하기 null 체크 우선 null을 체크하기 위해 tsconfig.ts에 아래 옵션을 추가해준다. "strict": true DOM조작할때 querySelector로 조회하면 엘리먼트가 없을때 null이 발생하는데, 그 상황을 잡기 위해서이다. html에 다음과 같은 p태그가 있다고 가정하자. 안녕하쇼 ts파일에서는 다음과 같이 narrowing하여 적을 수 있다. 그 이유는 title이 null과 Element의 union type이기 때문 let title = document.querySelector("#title"); if (title instanceof Element) { title.textContent = "반가워요"; } let title = document.querySelector('#title'.. 2022. 1. 15.
반응형