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"'.
'programming > javascript' 카테고리의 다른 글
[typescript] import,export 구문 (0) | 2024.07.17 |
---|---|
[nextjs] 환경변수 (0) | 2023.07.10 |
[rxjs 용어 정리] hot, cold Observable (0) | 2023.05.25 |
[rxjs] rxjs의 테스트 코드 작성(미완성) (0) | 2023.05.25 |
[typescript] 클래스 선언 방법 (0) | 2023.04.23 |