Union
이라고 함// sring | number
let bts1: string | number;
let bts2 = Math.random() > 0.5 ? taetae : 29;
bts2.toString(); // ok
bts2.toFixed(); // Error: property "toFixed" does not exist on type 'string |number'.
타입 가드
라고 한다.let animal = number | string;
animal = "rabbit";
animal.toUpperCase(); // ok: stirng
animal.toFixed();
// Error: property 'toFixed' does not exist on type 'string'
변수에 유니언 타입 애너테이션이 명시되고 초깃값이 주어질 때 값 할당 내로딩이 작동된다. 타입스크립트는 변수가 나중에 유니언 타입으로 선언된 타입 중 하나의 값을 받을 수 있지만, 처음에는 할당된 값의 타입으로 시작한다는 것을 이해헤야한다.
let bts = Math.randon() > 0.5 ? "taetae" : 29;
if(bts === "taetae") {
// bts. string 타입
bts.toUpperCase(); // ok
}
// bts : number | string 타입
bts.toUpperCase();
// Error : Property 'toUpperCase" does not exist on type 'string| number'
// Property 'toUpperCase' does not exist on type 'number'
let bts = Math.randon() > 0.5 ? "taetae" : 29;
bts.toString();
if(typeof bts === "string") {
// string
bts.toUpperCase();
if(typeof bts === "number") {
// number
bts.toFixed();
리터럴 타입
이라고 한다.const myState = "coughing"
1.리터럴 할당 가능성
: number와 string 과 같은 서로 다른 원시 타입이 서로 할당되지 못한다.
: 즉 0과 1 처럼 동일한 원시타입일지라도 서로 다른 리터럴 타입은 서로 할당 할 수 없다.
let bts:"Taetae" = "Taetae;
bts = "Blackpink"; // Error : Type "Blackpink" is not assignable to type "Taetae".
let someSong: "";
bts = someSong;
// Error : type 'string' is not assignable to type 'Taetae'.
: null과 undefined를 활성화 할 지 여부 결정하는 것.
let myName: string;
// strictNullChecks : false
myName = null; // ok
// strictNullChecks : true
myNamn = null; // Error : Type. 'null' is not assignable to type 'string'.
let breakfast = Math.random() > 0.5 ? "McDonald" : undefined;
if(breakfast) {
breakfast.toUpperCase(); // ok
breakfast.toUpperCase();
// Error : Object is possibly 'undefined'
breakfast && breakfast.toUpperCase(); // ok: string | undefined
breakfast?.toUpperCase();
let weekend = Math.random() > 0.5 && "Play Catch Ball";
if(weekend) {
weekend; // type: string
} else {
weekend; // type: false | string
}
let weekend: string;
weekend?.length;
// Error : Variable 'weekend' is used before being assingend.
weekend = "Play Catch Ball";
weekend.length; // ok
타입 별칭
: type 키워드를 이용해서 타입에 대한 변수를 생성한다.
타입별칭
dlatype HyungGu = ..;
type HyungGu = boolean | number | string | null | undefinedl
let HyunGuFirst: HyunGu;
let HyunGuSecond: HyunGu;
let HyunGuThird: HyunGu;
[Reference]
1. Learning typeScript(조시 골드버그/고승원/한빛미디어_2023)