타입스크립트 부분을 지웠을 때 올바르게 동작하는 자바스크립트 코드여야 한다.
JS 변환 시 사라지는 부분은 타입스크립트 코드이다.
타입 자리를 잘 기억해두자!
빈 배열을 선언할 때 타입 지정을 꼭 해주어야한다. 안그러면 never 타입이 자동으로 추론되는데 never 타입이 지정되면 아무것도 할 수 없다. never에 대해서는 따로 정리하자.
const head = document.querySelector('#header')!;
! 를 붙이면 null , undefined 가 아님을 보증하는 방식이다. → 비추천! 왜냐 세상에 절대는 없음!
! 을 안붙이면 head 의 타입 추론은 Element | null
이 나온다.
type World = 'world'; // 이건 뭐 .. 거의 원시값 생성 수준 아님?
type Greeting = `hello ${World}`;
// 근데 이걸 언제쓰면 좋냐..
type World = 'world' | 'hell';
type Greeting = `hello ${World}`;
const c: Greeting = 'hello world' <- hello world, hello hell 둘 중 고를 수 있음.
function rest(a, ...args: string[]){
console.log(a, args);
}
rest('1', '2', '3', '4'); // 1, [2, 3, 4]
rest 파라미터에 타입을 지정해준다.
const tuple: [string, number] = ['1', 2];
tuple[2] = 'hello'; // 오류남
tuple.push('hello'); // 오류 안남 .. 타스가 갓벽은 아님 이런거까진 못 막는다.
문제1. List Filtering
In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.
Example
filter_list([1,2,'a','b']) == [1,2]
filter_list([1,'a','b',0,15]) == [1,0,15]
filter_list([1,2,'aasf','1','123',123]) == [1,2,123]
function filter_list(arr) {
return arr.filter(v => typeof v === 'number');
}
이외에도 함수 인자를 map에서 타입 검사 등 방법이 있음.
function filter_list(l) {
return l.filter(Number.isInteger);
}
음 .. 래퍼타입을 이용해 숫자인지 확인하는 방법을 처음알았다.. Array.isArray처럼 있구나 ... 이게 더 가독성 있어보이기도 하다 .
알아볼 키워드