코드 정보에 입각한 추론 - Only TypeScript
- 유니언 union : 값에 허용된 타입을 두 개 이상의 가능한 타입으로 확장하는 것
- 내로잉 narrowing : 값에 허용된 타입이 하나 이상의 가능한 타입이 되지 않도록 좁히는 것
let math = Math.random() > 0.5 // let math: string | undefined
? undefined
: "Hello~"
undefined
나 string
**|
(수직선) 연산자** 사용let thinker: string | null = null;
if(Math.random() > 0.5){
thinker = "ME!"; //Ok
}
유니언 타입 선언의 순서는 중요 ❌, 앞 뒤 바껴도 똑같이 취급한다.
let person = Math.random() > 0.5
? "Emily"
: 82;
person.toString();
person.toUpperCase();
// Error: Property 'toUpperCase' does not exist on type 'string | number'.
// Property 'toUpperCase' does not exist on type 'number'.
person.toFixed();
// Error: Property 'toFixed' does not exist on type 'string | number'.
// Property 'toFixed' does not exist on type 'string'.
let a : number | string;
a = "apple"
//let a : number string = "apple" //축약가능
a.toUpperCase(); //Ok: string
a.toFixed();
//Error: Property 'toFixed' does not exist on type 'string'.
if문
을 통해 변수의 값을 좁히는 방법을 사용!// scientist : number | string의 타입
let scientist = Math.random() > 0.5
? "Franklin"
: 51;
if(scientist === "Franklin"){
// scientist : string의 타입
scientist.toUpperCase(); //Ok
}
// scientist : number | string의 타입
scientist.toUpperCase();
//Error : Property 'toUpperCase' does not exist on type 'string | number'.
//Property 'toUpperCase' does not exist on type 'number'.
만약 변수가 여러 타입 중 하나?
일반적으로 필요한 타입과 관련된 검사 want!
타입스크립트는 강제로 코드를 안전하게 작성할 수 있도록 하는 고마운 언어
let researcher = Math.random() > 0.5
? "Franklin"
: 51;
if(typeof researcher === "string"){
researcher.toUpperCase(); //Ok string
}
//! 논리적 부정, else문
if(!(typeof researcher === "string")){
researcher.toFixed(); //Ok number
}else {
researcher.toUpperCase(); //Ok string
}
//삼항 연산자
typeof researcher === "string"
? researcher.toUpperCase() //Ok: string
: researcher.toFixed(); //Ok: number
const philosopher = "Hypatia"; // type: "Hypatia"
각 원시 타입은 해당 타입이 가질 수 있는 가능한 모든 리터럴 값의 조합
→ 즉, 원시타입 == 해당 타입의 가능한 모든 리터럴 값의 집합
let specificallyAda : "Ada";
specificallyAda = "Ada"; //ok
specificallyAda = "Aron"
//Error: Type '"Aron"' is not assignable to type '"Ada"'
let someString= "";
specificallyAda = someString;
//Error: Type 'string' is not assignable to type '"Ada"'.
strict null checking
라고 부르는 타입 시스템 영역, “잠재적으로 정의되지 않은 undefined 값”으로 작업할 때 강력!const firstName: string = null;
strictNullChecks
: 엄격한 null 검사 활성화 여부 결정"strictNullChecks": true
설정 시, 모든 데이터 타입은 null
, undefined
를 할당 받을 수 없다."strictNullChecks": false
설정 시let nameMaybe = Math.random() > 0.5
? "Tony"
: undefined;
nameMaybe.toLowerCase();
//Potential runtime error: Cannot read property 'toLowerCase' of undefined.
"strictNullChecks": true
설정 시let nameMaybe = Math.random() > 0.5
? "Tony"
: undefined;
nameMaybe.toLowerCase();
//Error: Object is possibly 'undefined'.
타입스크립트 모범사례는 엄격한 null 검사를 활성화하는 것!
false, 0, -0, 0n, “”, null, undefined, NaN
let geneticist = Math.random() > 0.5
? "Babara"
: undefined;
if(geneticist){
geneticist.toLowerCase() //Ok: string
}
geneticist.toLowerCase();
//Error: Object is possibly 'undefined'.
geneticist && geneticist.toUpperCase(); //Ok: string | undefined
geneticist?.toUpperCase(); //Ok: string | undefined
&&
,?
연산자로 참 여부 확인 가능string | undefined
값에 대해 알고 있는 것이 falsy라면 그것이 빈 문자열인지 undefined인지는 알 수 없음let biologist = Math.random() > 0.5 && "Rachel"
if(biologist){
biologist; //타입 string
}else{
biologist; //타입 false | string
}
let me: string;
me?.length;
//Error: Variable 'me' is used before being assigned.
me = "kim"
me.length; //Ok
let me: string | undefined
me?.length; //Ok
me = "kim"
me.length; //Ok
📚 러닝타입스크립트