IT/TypeScript

[TypeScript] array/readonly/tuple/undefined/null/any/void/never/unknown

Huitopia 2024. 1. 11. 02:51
728x90

Array

let a : number[] = [1];
let b : string[] = []"li"];
let c : boolean[] = [true];
let d : array = []; // error

let e = [1, 2]; // 타입을 지정하지 않아도 타입스크립트가 추론함

 

readonly

요소들을 읽기 전용으로 만들 수 있음

type Age = number
type Name = string
type Info = {
    readonly name:Name, // readonly가 앞에 붙으면 수정 불가능
    age?:Age
}

const playerMaker = (name:string) : Info => ({name});
const mi = playerMaker("mi")
mi.age = 10;
mi.name = "he"; // error

const num: readonly number[] = [1, 2, 3];
num.push(2); // error

 

Tuple

array를 생성하는데 최소한의 길이를 갖고 특정 위치에 특정 타입이 있어야함

const option: [string, number, boolean] = ["L", 100, true];
option[0] = "XL";
option[0] = 90; // error

 

undefined / null

let a : undefined = undefined;
let b : null = null;

 

 

any

비어있는 값들을 쓰면 기본값이 any가 됨

let a = [] // let a: any[] a를 any의 array라고 생각함

any는 주로 type을 빠져나오고 싶으면 사용 ⇒ any는 아무 타입이나 다 됨

최대한 any 사용을 지양해야함

const a : any[] = [1, 2, 3, 4];
const b : any = true;

const c = a + b;
console.log(c) // "1,2,3,4true"

// any 사용하지 않고 합치기
const a : (number | boolean)[] = [];
const b = true;
a.push(1, 2, 3, 4);
a.push(b)
console.log(a) // [1, 2, 3, 4, true]

 

void

function hello(){
    console.log('x')
}

function hello():void{
    console.log('x')
}

아무것도 return 하지 않는 함수 대상으로 사용

함수가 아무것도 return 하지 않는다는 것을 자동으로 인식해서 따로 지정해줄 필요는 없음

function hello(){
    console.log('x')
}
const a = hello();
a.toUpperCase() // error return 값 없어서

function hello(){
    console.log('x')
    return "a"
}
const a = hello();
a.toUpperCase() // 정상 작동
console.log(a) // "a"

 

never

함수가 절대 return 하지 않을 때 발생

function a():never{
    return "x" // error
}

function a():never{
    throw new Error("xxx") // return 하지 않고 오류 발생 함수
}

console.log(a()) // xxx

function b (name : string | number) {
    name + 1 // error name이 number일지 string일지 모름
}

 

unknown

변수의 타입을 미리 알지 못 할 때 사용(예: api)

let a: unknown;

let b = a + 1; // error a의 type을 알아야함

if(typeof a === 'number') {
    let b = a + 1 // if절에서 확인했기 때문에 error 없음
}
728x90