-
[TS] 타입 시스템, 유니언과 리터럴codeStates front-end/Typescript 2023. 3. 6. 17:43반응형
📌 타입 시스템
📍 타입의 종류
🔗 타입스크립트의 기본 윈시 타입
null undefined boolean string number bigint symbol
🔗 할당가능성
함수 호출이나 변수에 값을 제공할 수 있는지 여부를 확인하는 것
'Type... is not assignable to type ...' // 할당가능성 오류
🔗 타입 에너테이션
초기 다입을 유추할 수 없는 변수는 진화하는 any
let rocker; // 진화하는 any rocket = "John" // 타입 : string
📍 유니언과 리터럴
유니언 : 값에 허용된 타입을 두 개 이상의 가능한 타입으로 확장하는 것
리터럴 : 값에 허용된 타입이 하나 이상의 가능한 타입이 되지 않도록 좁히는 것
🔗유니업 타입
let mathematicain = Math.random() > 0.5 ? undefined : "Math Goldberg";
👉🏻 mathematicain은 undefined 이거나 String일 수 있다.
이와 같이 이거 혹은 저거 타입을 유니언이라고 한다.
let thinker : string | null; // 연산자를 이용해 유니언 타입을 나타냄 if (Math.random() > 0.5){ thinker = "~~~" }
🔗 유니언 속성
값이 유니언 타입일 때 유니언으로 선언한 모든 가능한 타입에 존재하는 멤버 속성에만 접근할 수 있다.
예를 들어 number | string 일 경우 toString() 사용 가능하나, toUpperCase(), toFixed() 사용 불가
toUpperCase()는 number 타입에 없고, toFixed()는 string 타입이 없기 때문이다.
🔗 내로잉
값이 정의, 선언 혹은 이전에 유추된 것보다 더 구체적인 타입임을 코드에서 유추하는 것
타입을 좁히는데 사용할 수 있는 논리적 검사를 타입가드라고 한다.
let admiral : number | string; admiral = "Grace Hopper"; admiral.toUpperCase(); // ok : string admiral.toFixed(); // Error why? type 'string' X
조건 검사를 통한 내로잉
if문을 통해 변수의 값을 좁히는 방법
let scientist = Math.random() > 0.5 ? "Rosalind Franklin" : 51; if (scientist === "Rosalind Franklin"){ scientist.toUpperCase(); // ok } scientist.toUpperCase(); // Error
typeof 검사를 통한 내로잉
typeof 연산자를 사용하여 타입을 좁히는 방법
let scientist = Math.random() > 0.5 ? "Rosalind Franklin" : 51; if (typeof scientist === "string"){ scientist.toUpperCase(); // ok : string }
참 검사를 통한 내로잉
참 또는 truthy는 &&연산자 또는 if문처럼 boolean문맥에서 true로 간주된다
JS 👉🏻 false,0, -0, 0n, null, undefined, NaN처럼 falsey로 정의된 값을 제외한 모든 값은 모두 참
TS 👉🏻잠재적인 값 중 truthy로 확인된 일부에 한에서만 타입을 좁힐 수 있다
let scientist = Math.random() > 0.5 ? "Rosalind Franklin" : undefined; if (scientist) { scientist.toUpperCase(); // ok } scientist.toUpperCase(); // Error geneticist && geneticist.toUpperCase(); // ok : string | undefined geneticist?.toUpperCase(); // ok : String | undefined
🔗 리터럴 타입
원시 타입 값 중 어떤 것이 아닌 특정 원싯값으로 알려진 타입이 리터럴 타입
문자열 중에서도 string 타입은 존재할 수 있는 모든 가능한 문자열의 집합
그 중에서 "~~"명시한다면 하나의 문자열만을 나타냅니다
리터럴 할당 가능성
let specificallAda: "Ada"; specificallAda = "Ada"; // ok // specificallAda은 Ada로 선언했으므로 Ada 할당은 가능하나 다른 값으론 할당 불가 specificallAda = "Byron"; // Error // string 타입에 값 할당 x let someString = ""; specificallAda = someString; //Error // 그러나 타입스크립트에선 타입 ":)"의 값,":)"는 someString 변수에 할당 가능 let someString = ":)"; specificallAda = someString; // ok
엄격한 null 검사
리터럴로 좁혀진 유니언의 힘은 타입스크립트에서 엄격한 null 검사라 부르는 타입 시스템 영역인
"잠재적으로 정의되지 않은 undefined 값"으로 작업할 때 특히 두드러진다
십억 달러의 실수
"잠재적으로 정의되지 않은 undefined 값"으로 작업
십억 달러의 실수는 다른 타입이 필요한 위치에서 null값을 사용하도록 허용하는 많은 타입 시스템을
가리키는 업계 용어이다
const firstName : string = null;
엄격한 null 검사를 활성해야만 코드가 null 또는 undefined 값으로 인한 오류로부터 안전한지 여부 파악 가능
초깃값이 없는 변수
JS의 초깃값 👉🏻 undefined
🤔 undefined를 포함하지 않는 타입으로 변수를 선언한 다음 값을 할당하기 전에 사용하려고 한다면? Error
undefined가 포함 되어 있는 경우에는 오류 x
let mathematicain: string | undefined; mathematicain?.length; //ok mathematicain = "Mark Goldberg"; mathematicain.length; //ok
🔗 타입 별칭
재사용하는 타입에 더 쉬운 이름을 할당하는 타입 별칭이 있다
// type MyName = ...; type data = boolean | number | string | null | undefined; let data1 : data; let data2 : data; let data3 : data; // 타입 별칭 결합도 가능하다 type Id = number | string; // IdMabe -> number | string | undefined | null type IdMaybe = Id | undefined | null;
반응형'codeStates front-end > Typescript' 카테고리의 다른 글
[TS] 클래스 (0) 2023.03.20 [TS] 인터페이스 (0) 2023.03.12 [TS] 배열과 튜플 (0) 2023.03.12 [TS] 함수 (0) 2023.03.12 [TS] 객체 (0) 2023.03.06