개발 공부/Typescript
object를 enum처럼 사용하기
차정
2024. 2. 23. 14:45
const enum EDirection {
Up =3,
Down,
Left,
Right,
}
function enumWalk(dir: EDirection) {}
enumWalk(EDirection.Down);
const ODirection = {
Up: 0,
Down: 1,
Left: 2,
Right: 3,
} as const
//type ODirectionKey = "Up" | "Down" | "Left" | "Right"
// 객체의 키만 뽑아서 타입으로 만듦
//type ODirectionKey = keyof typeof ODirection;
// 객체 자체가 타입 -> enum처럼 사용가능
type Key = typeof ODirection[keyof typeof ODirection] ;
function objectRun(dir: Key) {}
objectRun(0)
objectRun(ODirection.Down)
objectRun(1)
as const 를 사용하면 이 객체를 그대로 타입으로 사용하겠다는 뜻이 됩니다.
그래서 타입으로 그 객체 그대로 제시해줍니다.
as const 없애면 타입이 객체의 값 그대로 저장되지 않는다. 타입이 number로 범위가 커진다.
as const 를 넣어서 타입의 범위를 좁혀주는것이 좋다.
TS Playground - An online editor for exploring TypeScript and JavaScript
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
www.typescriptlang.org
제로초 강의