typescript conditional Type 조건부타입

BackEnd_Ash.log·2021년 8월 18일
0

typescript

목록 보기
13/17

this is the new way of decision to type
reference

T extends U ? X : Y

📌 What is extends in typescript?

you need to understand about extends calculation of typescript for understand conditional type

TypeScript is maed a type system based on duck typing.
duck typing is also structural typing

✅ Base

interface Person {
  name: string;
}

interface Student {
  name: string;
  studentNo: string;
}

const person: Person = {
  name: "ash person",
};

const student: Student = {
  name: "ash student",
  studentNo: "111",
};

// (O) Student는 Person의 모든 프로퍼티를 가지고 있으므로, OK
const person2: Person = student;
// (X) Person은 Student의 studentNo를 가지고 있지 않으므로, 컴파일 에러
const student2: Student = person;
export {};

interface Human {
  intro(): void;
}

interface Student extends Human {
  study(): void;
}

type Person = Student extends Human ? number : string; // type Person = number

const master : Person = "string";
const jung   : Person = 10;

✅ extends

type IsStringType<T> = T extends string ? "yes" : "no";
type T1 = IsStringType<string>; // type T1 = "yes"
type T2 = IsStringType<number>; // type T2 = "no"

maybe you think that is it "삼항연산자"??

not it's "삼항연산자" but extends on typescript

✅ When to use conditional type?


export {};

function getPerson(name: string): string;
function getPerson(id: number): string;
function getPerson(property: any): string {
  if (typeof property === "string") {
    return "getPerson by name string";
  } else if (typeof property === "number") {
    return "getPerson by id number";
  }
  return "customer";
}

console.log(getPerson(28)); //getPerson by id number
console.log(getPerson("master")); // getPerson by name string

you add a function using overroad , you have to add the "if" again.

if you use conditional type , you can write concise code

export {};

type IdOrName<T extends number | string> = T extends number ? number : string;
function getPerson(idOrName: IdOrName<number | string>): string {
  if (typeof idOrName === "string") {
    return "getPerson by name string";
  } else if (typeof idOrName === "number") {
    return "getPerson by id number";
  }
  return "customer";
}

console.log(getPerson(28)); //getPerson by id number
console.log(getPerson("master")); // getPerson by name string
profile
꾸준함이란 ... ?

0개의 댓글