type OneToFive = 1 | 2 | 3 | 4 | 5;
type Bools = true | false;
function iTakeFoo(foo: 'foo') { }
const test = {
someProp: 'foo'
};
iTakeFoo(test.someProp); // Error: Argument of type string is not assignable to parameter of type 'foo'
function iTakeFoo(foo: 'foo') { }
const test = {
someProp: 'foo' as 'foo'
};
iTakeFoo(test.someProp); // 오케이!
function iTakeFoo(foo: 'foo') { }
type Test = {
someProp: 'foo',
}
const test: Test = { // 타입을 붙임 - someProp의 추론된 타입은 항상 === 'foo'
someProp: 'foo'
};
iTakeFoo(test.someProp); // 오케이!
/** 문자열 목록으로 K:V를 만드는 유틸리티 함수 */
function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
return o.reduce((res, key) => {
res[key] = key;
return res;
}, Object.create(null));
}
/** 문자열 목록으로 K:V를 만드는 유틸리티 함수 */
function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
return o.reduce((res, key) => {
res[key] = key;
return res;
}, Object.create(null));
}
/**
* 문자열 열거형을 만드는 예시
*/
/** K:V 생성 */
const Direction = strEnum([
'North',
'South',
'East',
'West'
])
/** 타입 생성 */
type Direction = keyof typeof Direction;
/**
* 문자열 열거형을 사용하는 예시
*/
let sample: Direction;
sample = Direction.North; // 오케이
sample = 'North'; // 오케이
sample = 'AnythingElse'; // 오류!