TypeScript

· TypeScript
Zod?💡스키마 선언 및 유효성 검사 라이브러리 🤔 Zod가 필요한 이유는 무엇일까TypeScript의 한계 때문이다.TypeScript는 컴파일 시점에서만 타입에러를 잡아낼 수 있다.➡️ 즉, 런타임 단계에서의 타입 에러는 잡을 수가 없다.또한 TypeScript는 문자열이나 원하는 숫자 범위를 강제하거나 number타입을 더욱 구체적으로 정수나 실수로의 구분이 불가능하다.설치pnpm add zod # pnpmTypeScript 4.5 이상가능tsconfig.json 에 "strict": true 설정이 되어있어야 한다.사용 //문자열만 허용 const Schema1 = z.string(); // 문자열이 있으면 4~20까지 허용, optional일 경우 undefined도 허용 ..
· TypeScript
문제https://github.com/type-challenges/type-challenges/blob/main/questions/00003-medium-omit/README.md type-challenges/questions/00003-medium-omit/README.md at main · type-challenges/type-challengesCollection of TypeScript type challenges with online judge - type-challenges/type-challengesgithub.com✅ 내 풀이type MyOmit = { [P in keyof T as P extends K ? never : P]: T[P];};K는 T의 하위니깐 타입 좁히고, Exclude를..
· TypeScript
📌 문제https://github.com/type-challenges/type-challenges/blob/main/questions/00011-easy-tuple-to-object/README.ko.md type-challenges/questions/00011-easy-tuple-to-object/README.ko.md at main · type-challenges/type-challengesCollection of TypeScript type challenges with online judge - type-challenges/type-challengesgithub.com🤔 풀이과정T[number] 은 요소들을 전부 유니온으로 만들어준다. T는 튜플 또는 readonly 배열 타입 이여야 한다. t..
· TypeScript
📌 문제https://github.com/type-challenges/type-challenges/blob/main/questions/00007-easy-readonly/README.ko.md type-challenges/questions/00007-easy-readonly/README.ko.md at main · type-challenges/type-challengesCollection of TypeScript type challenges with online judge - type-challenges/type-challengesgithub.com✅ 답type MyReadonly = { readonly [K in keyof T]: T[K] }; T 안의 key를 돌면서 T[k] Readonly로 바꾸..
· TypeScript
📌 문제https://github.com/type-challenges/type-challenges/blob/main/questions/00004-easy-pick/README.ko.md type-challenges/questions/00004-easy-pick/README.ko.md at main · type-challenges/type-challengesCollection of TypeScript type challenges with online judge - type-challenges/type-challengesgithub.comT에서 K 프로퍼티만 선택해 새로운 오브젝트 타입을 만드는 내장 제네릭 Pick을 이를 사용하지 않고 구현하기 !!😭 나의 실수우와 보자마자 짱 쉽다 하고 풀었는데 ....
· TypeScript
앞에 Type Narrowing에 대해 정리했지만 타입 가드를 들었을 때 둘이 같은거라고 생각했다. 하지만 약간의 차이가 있고 알고보면 완전히 다른 것이라는 것을 알 수 있다. 예를 들어서 설명하는 것이 쉽다. const value: unknown = "hello";if (typeof value === "string") { // 타입 가드 사용 ! console.log(value.toUpperCase()); // 이렇게 타입 가드후 타입 내로잉을 거친다. }unknown을 예로 들어 설명하면 쉽다. unknown은 any와 함께 최상위 타입에 속한다. 그 말은 즉 타입이 구체적이지 않고 추상적이라는 말이다. 여기서 최상위 타입이란?모든 타입이 할당 가능한 타입을 의미한다. ➡️ 즉 타입이 매우 추상적이..
· TypeScript
📌 클래스 메서드(멤버 함수)매개변수 타입이나 기본값을 지정하지 않으면 any타입을 기본 값으로 가진다. 메서드를 호출하려면 허용 가능한 인수가 필요, 재귀 함수가 아니라면 대부분 반환 타입 유추 가능메서드 호출시 올바른 타입의 인수가 올바른 수로 제공되는지 확인하기 위해 타입 검사 실시📌 클래스 속성(attribute)클래스의 속성을 읽거나 쓰려면 명시적으로 선언해야 한다.class FieldTrip { destination : string; // 불필요 constructor(destination : string){ // 여기서 이미 쓰였기 때문에 타입 추론을 해준다. this.destination = destination; console.log(`We're ..
· TypeScript
타입스크립트에서 리터럴 타입을 최대한 그대로 유지하면서 그 값을 readonly로 만들어주는 기능을 한다. primitive 타입의 값 뒤에 as const 연산자가 붙으면 값 자체가 타입이 된다.(Readonly)object 타입의 값 뒤에 as const 연산자가 붙으면 read-only 타입이 된다. const assertion은 enum멤버에 대한 참조 또는 string, number, boolean, array, object 리터럴에만 적용할 수 있다.const a = [1, 2, 3] as const;a는 읽기 전용이 되었기 때문에 a.push와 같은 메서드를 사용하지 못한다.타입스크립트는 let은 값이 바뀔 수 있다고 인식하여 일반적인 값인 number로 타입을 추론하게 된다. 반면에 con..
· TypeScript
📌 인터페이스 (Interface)interface A { a: string; b: string;}📌 타입(Type)//🚨 오류 발생, 중복(재선언 불가능)type A = { name: string;};type A = { age: number;}; interface와 type모두 컴파일 시점에 체크하고 JavaScript로 변환되면 사라지게 된다.type : 블록 스코프, 중복 선언 불가interface: 중복 선언 가능-> 같은 이름 여러개 있을 경우 모두 합쳐짐( 아래 설명: 병합 )//✅ 재선언 가능interface A { name: string;}interface A { age: number;}인덱스 시그니처와 속성 타입 오류interface Novel { title:..
· TypeScript
any아무 검증을 하지 않아서 뭐든지 할 수 있다.const value: any = "hello";value.toUpperCase(); // okvalue(); // ok ❌ (에러 안 남)value.nonExistent.prop(); // ok ❌에러가 나지 않고 , 다 통과해버려서, 런타임에서 터질 위험이 있다.unknown뭐든 담을 수 있지만 쓸 때는 체크가 필요하다.const value: unknown = "hello";// value.toUpperCase(); 에러: 'unknown'은 직접 쓸 수 없음if (typeof value === "string") { // 타입 가드 사용 ! console.log(value.toUpperCase()); // 이렇..
unemployedMan
'TypeScript' 카테고리의 글 목록