타입스크립트(ZeroCho) 기본문법
타입 추론
ts자체에서 추론해주는 타입이 있으면 그냥 그대로 사용하면 된다.
ts의 추론이 틀렸거나! any로 타입을 지정했을때,ts가 추론하지 못하는 경우에만 집접 타이핑이 필요하다.
이유는 타입이 '5'라고 정확하게 되어있는데 const a는 '5'를 변경할 수 가 없는데 만약
const a: string = '5'
이렇게 string으로 지정을 해버리면 '5'라는 정확한 타입에서 string이라는 명확하지 못한 애매한 타입이 되어버린다.
이런식으로 함수도 타입추론을 해주는데 리턴값을 없애도 result의 타입은 number로 나온다.
다만 매개변수의 타입을 적어주지 않으면 타입추론이 any로 나오기 때문에 매개변수에는 꼭 타입을 지정해줘야 한다.
배열도 타입추론이 가능하다.
다만 저렇게 파이프가 있으면 타입추론이 잘못된거기 때문에 직접 타입을 타이핑 해주면 된다.
웬만하면 타입 추론에 맡겨야 한다! 타입은 최대한 짧게 작성을 해야 한다!
never타입과 느낌표
[] 빈배열에 never라는 타입이 나온다.
빈배열에는 꼭 타입을 지정을 해줘야 한다.
try {
const array:string[] = []; // noImplicitAny가 false일 때
array[0];
} catch(error) {
error;
}
Element
head에는 Element를 쓸 수 있다.
head에 Element 또는 null이 올 수 있다.
만약 null이 아니라고 확정할 수 있다면 끝에 '!' 를 붙여주면 된다.
const head = document.querySelector('#head')!;
다만, 절대란 없기 때문에 !를 쓰는건 추천하지 않는다. ! 대신 if를 써야한다.
const head = document.querySelector('#head');
if (head) {
console.log(head);
}
원시 래퍼 타입, 템플릿 리터럴 타입, rest, 튜플
string과 String은 다르다. 무조건 소문자로 써야한다!!!
const a: string = 'hello';
const b: String = 'hell';
템플릿 리터럴 타입이 존재한다.
type World = "world" | "hell";
const a: World = 'world'
const b = `hello ${a}`;
// type Greeting = "hello world"
type Greeting = `hello ${World}`;
const c: Greeting = 'hello hell'
배열
let arr: string[] = [];
let arr2: Array<string> = [];
function rest(...args: string[]) {}
// rest가 string타입이기 때문에 1,2,3도 문자열이어야 한다.
rest('1','2','3');
튜플
const tuple: [string, number] = ['1', 1];
tuple[2] = 'hello'; // 에러가 난다.
tuple.push('hello'); // 정상작동한다.
enum, keyof, typeof
enum
여러개의 변수들을 하나로 묶고 싶을 때 사용한다.
만약 Up이 3이라면 순서대로 3, 4, 5, 6이 된다.
const enum EDirection {
Up, // 0
Down, // 1
Left, // 2
Right, // 3
}
const a = EDirection.Up;
const c = EDirection.Left;
타입추론을 확인해보면 0,1,2,3으로 정확한 타입을 사용하고싶은데 number로 타입추론이 애매하게 되버렸다.
const ODirection = {
Up: 0,
Down: 1,
Left: 2,
Right: 3,
} as const;
그럴때 as const로 그대로 사용하겠다라는 의미로 사용하면 값을 상수로 사용하겠다라는 의미가 된다.
readonly로 되며 읽기전용으로 값이 타입이 된다.
keyof, typeof
const obj = {a:'123',b:'hello',c:'world'} as const
// obj에서 key만 뽑아내고 싶다면?
type key = keyof typeof obj // 'a','b','c'
// obj에서 value만 뽑아내고 싶다면?
type key1 = typeof obj[keyof typeof obj] // '123','hello','world'
union(|)과 intersection(&)
type A = { a: string };
const a: A = { a: 'hello' };
interface B { a: string }
const b: B = { a: 'hello' };
간단하게 사용하고 싶으면 type을 사용하고 추후 객체지향 프로그래밍을 사용할땐 interface를 사용해야 한다.
union(|) 또는이라도고 부른다.
다만 타입추론이 제대로 되지 않는다.
function add(x: string | number, y: string | number): string | number { return x + y }
const result: string | number = add(1, 2) // 결과가 string으로도 나올 수 있다.
위 코드는 잘못된 타입지정이기 떄문에 리턴 타입에 string | number은 맞지 않는다.
intersection(&)
const a 는 위에 타입이 조건이 두개 다 만족해야하나 하나만 사용됬을 경우 타입에러가 난다.
type A = {hello:'world'} & {choi:'uri'}
const a: A ={hello:'world', choi:'uri'}
위 코드처럼 두개 다 사용을 해야 대입 가능하다.
&일때는 모든 속성이 다 있어야 한다.
|일때는 속성중 하나만 있어도 된다.