programming/javascript

[typescript] typeof, keyof

worldint 2023. 5. 30. 10:59

1.typeof

객체를 객체형태의 타입으로 만들어 주는 키워드

const obj = {
  red : "apple",
  blue : "sky",
  yellow : "flower",
}

이런 객체가 있을 때 

obj에 typeof를 사용하면 아래처럼 타입에 할당이 가능하다

type A = typeof obj
type A = {
  red : "apple";
  blue : "sky";
  yellow : "flower";
}

2.keyof

객체형태의 type의 key들 로 union type을 만들어줌

type A = {
  red : "apple";
  blue : "sky";
  yellow : "flower";
}

type union = keyof A

//type union = "red" | "blue" | "yellow"

keyof를 enum에도 사용할 수 있는데

enum obj {
  red = "apple",
  yellow = "banana",
  green = "cucumber",
}

그때는 keyof typeof A이런식으로 사용해야 한다

type Key = keyof typeof obj;

let ob3: Key = "red";

객체에는 keyof를 쓸 수 없고

enum에는 keyof를 쓸 수는 있는데 아래처럼 저런 이상한 union type이 만들어지게 된댜

type Key = keyof obj; //이렇게 하면 아래의 코드에서 에러가 나온다

let ob1:Key = "red"

//Type '"red"' is not assignable to type 'number | unique symbol | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | ... 26 more ... | "sup"'.