Open doong-jo opened 1 year ago
enum
s Are Union enum
sTypescript가 초기의 enum은 같은 타입의 숫자 집합
enum E {
Foo = 10,
Bar = 20,
}
E.Foo
와 E.Bar
는 type E
로 예상되는 모든 것에 할당 가능하다는 것.
value에 해당하는 값을 직접 할당하면 에러
function takeValue(e: E) {}
takeValue(E.Foo); // works
takeValue(123); // error!
TS 2.0에서 enum literal type이 도입. enum 자체를 union으로 사용하여 subset을 만들 수도 있음.
// Color is like a union of Red | Orange | Yellow | Green | Blue | Violet
enum Color {
Red, Orange, Yellow, Green, Blue, /* Indigo, */ Violet
}
// Each enum member has its own type that we can refer to!
type PrimaryColor = Color.Red | Color.Green | Color.Blue;
function isPrimaryColor(c: Color): c is PrimaryColor {
// Narrowing literal types can catch bugs.
// TypeScript will error here because
// we'll end up comparing 'Color.Red' to 'Color.Green'.
// We meant to use ||, but accidentally wrote &&.
return c === Color.Red && c === Color.Green && c === Color.Blue;
}
TS 5.0에서는 계산된 각 멤버에 고유한 타입을 생성하여 모든 enum을 union enum으로 만들 수 있음.
enum E {
Blah = Math.random()
}
const a: E.Blah = 10
### ``enum`` vs ``union type``
```ts
// enum
enum Fruit {
APPLE = 'APPLE',
BANANA = 'BANANA',
KIWI = 'KIWI'
}
// union type
type Fruit = 'apple' | 'banana' | 'kiwi'
대부분의 경우 union type으로 대체 가능함
https://engineering.linecorp.com/ko/blog/typescript-enum-tree-shaking
// Namespace definition
namespace MyNamespace {
export const myVariable = 10;
}
// Accessing the exported member const value = MyNamespace.myVariable;
- modules 방식은 top scope에 모든 것들을 선언하여 직접 호출이 가능
### package 용량 감소
- 63.5MB에서 35.6MB로 약 40% 감소
- 중복되는 파일들 제거
- bundle file의 indent 축소 (4space -> 2space)
- ``tsc.js``와 ``typingsInstaller.js``에서의 tree shaking
TypeScript 5
Decorators
Before
Use Decorator
주의할 점
class 내부
에서만 사용할 수 있다.runtime에 호출
된다.실제 활용 사례
에러 클래스 생성 및 로깅 로직은 decorator로 재사용 가능하도록 활용
const Type Parameters
TS Playground