러닝 타입스크립트를 읽고 요약한 내용입니다.
let thinker: string | null = null; // 초깃값은 null이지만,
if(Math.random() > 0.5) {
thinker = "Susanne Langer"; // null 대신 string이 될 수 있음
}
boolean | number
나 number | boolean
모두 똑같이 취급합니다.let physicist = Math.random() > 0.5 ? "Marie Curie" : 84;
physicist.toString();
physicist.toUpperCase(); // physicist.toUpperCase is not a function
physicist.toFixed(); // physicist.toUpperCase is not a function
let admiral: number | string;
admiral = "Grace Hopper";
admiral.toUpperCase(); // Ok: string
admiral.toFixed(); // admiral.toFixed is not a function
let scientist = Math.random() > 0.5 ? "Rosalind Franklin" : 51;
if (scientist === "Rosalind Franklin") {
scientist.toUpperCase(); // OK
}
scientist.toUpperCase(); // [ERR]: scientist.toUpperCase is not a function
typeof
검사를 통한 내로잉도 가능합니다. typeof
검사는 타입을 좁히기 위해 자주 사용하는 실용적인 방법입니다.let researcher = Math.random() > 0.5 ? "Rosalind Franklin" : 51;
if(typeof researcher === 'string') {
researcher.toUpperCase(); // Ok: string
}
let specificallyAda: "Ada";
specificallyAda = "Ada"; // OK
specificallyAda = "Byron"; // Type '"Byron"' is not assignable to type '"Ada"'.
let someString = "";
specificallyAda = someString; // Type 'string' is not assignable to type '"Ada"'
someString = specificallyAda; // Ok
undefined
값’으로 작업할 때 특히 두드러집니다. strictNullChecks
는 엄격한 null
검사를 활성화할지 여부를 결정합니다. strictNullChecks
를 활성화하면 코드가 null
또는 undefined
값으로 인한 오류로부터 안전한지 여부를 쉽게 파악할 수 있습니다.let nameMaybe = Math.random() > 0.5 ? "Tony Hoare" : undefined;
nameMaybe.toLowerCase(); // nameMaybe' is possibly 'undefined'.
false
, 0
, -0
, 0n
, “”
, null
, undefined
, NaN
처럼 falsy로 정의된 값을 제외한 모든 값은 모두 참입니다. 잠재적인 값 중 truthy로 확인된 일부에 한해서만 변수의 타입을 좁힐 수 있습니다.let geneticist = Math.random() > 0.5 ? "Barbara McClintock" : undefined;
if(geneticist) {
geneticist.toUpperCase();
}
geneticist.toUpperCase(); // 'geneticist' is possibly 'undefined'.
type RawData = boolean | number | string | null | undefined;
let rawDataFirst: RawData;
let rawDataSecond: RawData;
let rawDataThird: RawData;
type SomeType = string | undefined;
console.log(SomeType); // 'SomeType' only refers to a type, but is being used as a value here.