반응형
SMALL
Array
- 같은 타입의 자료들을 모아놓음.
- 자바스크립트에서 객체.
let list: number[] = [1,2,3]; //선호
let list: Array<number> = [1,2,3];
let list: (number | string)[] = [1,2,"3"];
Tuple
let a: [string, number];
a = ["age", 30];
a = [23, "age"]; //error
a[3] = "name"; //error, 인덱스 2 이후에는 타입이 undefined가 됨.
길이가 정해져 있고, 앞뒤의 타입이 정확하고 다를 수 있는 자료형이다.
any
- 어떤 것이든 된다.
function returnAny(message: any): any {
console.log(message);
}
const any1 = returnAny('리턴은 anything');
any1.toString(); //undefined 이지만 에러가 뜨지 않는다.
//누수 방지
function leakingAny(obj: any) {
const a: number = obj.num;
const b = a + 2;
return b;
}
const c = leakingAny({num: 0});
- 사용하지 않는 것이 좋다.
- noImplicitAny 옵션은 any를 써야 하는데 쓰지 않으면 오류를 출력합니다.
- 객체를 통해 전파된다.
unknown
- 모르는 변수의 타입을 묘사할 때 any 대신에 사용.
- 동적 콘텐츠에 사용.
declare const maybe: unknown;
const aNum: number == maybe; //error, 바로 할당 불가.
//타입 가드
if(maybe === true) {
const aBool: bollean = maybe; //maybe의 타입이 true로 지정됨.
}
if(typeof maybe === 'string') {
const aStr: sttring = maybe; //maybe의 타입이 string이 됨.
}
never
- 일반적으로 리턴에 사용.
function error(message: string): never {
throw new Error(message);
}
function fail() {
return error("err");
}
function infLoop(): never {
while(true) {}
}
- 모든 타입의 subtype이며, 모든 타입에 할당 가능.
- never에는 할당 불가. (any도 불가)
- 잘못된 타입을 넣는 실수를 막고자 할 때 사용하기도 함.
void
- 값은 없고 타입만 있음.
function retVoid(message: string) { //void 타입으로 자동으로 추론.
console.log(message);
return; //유일하게 undefined만 가능.
}
const d = returnVoid('No return'); //d: void
반응형
'프론트개발 > TypeScript' 카테고리의 다른 글
[TypeScript] 인터페이스(Interface) (0) | 2022.07.19 |
---|---|
[TypeScript] 타입 호환성과 별칭 (0) | 2022.07.18 |
[TypeScript] 타입 시스템 (0) | 2022.07.18 |
[TypeScript] 타입 스크립트의 타입(1) (0) | 2022.07.16 |
[TS vs JS] 타입스크립트와 자바스크립트 (0) | 2022.07.15 |
댓글