[typescript] Type assertions, union type, literal type, alias
                                            
                                                
                                                
                                                
                                                
                                                
                                                 8440 단어  typescripttypescript
                    
Type Assertions
any 혹은 unkown 으로 선언해두고 참조할 때 타입을 assert함 (type 덮어쓰기)
// (1) as
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length; // (*)
// (2) angle-bracket
let someValue: unknown = "this is a string";
let strLength: number = (<string>someValue).length;  // (*)Union Type
하나 이상의 타입을 사용할 때 (more flexible)
function combine(input1: number | string, input2: number | string) {// (*)
  let result;
  
  if(typeof input1 === 'number' && typeof input2 === 'number') { // runtime type check
  	return input1 + input2;
  } else {
    return input1.toString() + input2.toString();
  }
  return result;
}
const combineAge = combine(21, 30);
const combineName = combine('Suyeon', 'Hanna');Literal Type
It allows an exact value which a string, number, or boolean must have.
- string / number / boolean
// string
function createElement(tagName: "img"): HTMLImageElement;
function createElement(tagName: "input"): HTMLInputElement;
function(reslut: 'img' | 'text') {
   if(result === 'text') {
    // ...
    } else {
    // ...
    }
}
// number
interface MapConfig {
  tileSize: 8 | 16 | 32;
}
setupMap({ tileSize: 16 });
// boolean
interface ValidationSuccess {
  isValid: true;
};Alias
Reusable custom type set.
type pet = 'cat' | 'dog';
type Combinable = string | number;
function combine(input1: Combinable, input2: Combinable){...}Author And Source
이 문제에 관하여([typescript] Type assertions, union type, literal type, alias), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@suyeonme/typescript-Type-assertions-union-type-literal-type-alias저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)