제네릭 함수
function fuc<T>(value:T):T{
return value;
}
제너릭 함수 - 프로미스
const promise = new Promise<number>((res,rej)=>{…}); //이런 형태가 되야 한다~~
타입 조작하기
인덱스드 엑세스 타입
interface Post {
title: string;
content: string;
author: {
id: number;
name: string;
age: number; // 추가
};
}
적용전)
function printAuthorInfo(author: { id: number; name: string, age: number }) {
// age 프로퍼티도 추가
console.log(`${author.id} - ${author.name}`);
}
적용후)
function printAuthorInfo(author: Post[“author”]) { //인덱스에 아예 없는 프로퍼티 또는 변수를 사용할수 없다!!
// age 프로퍼티도 추가
console.log(`${author.id} - ${author.name}`);
}
interface Person {
name: string;
age: number;
location: string; // 추가
}
function getPropertyKey(person: Person, key: keyof Person) { // key of Person 는 “name”|”age”|”location”과 같다
return person[key];
}
const person: Person = {
name: "이정환",
age: 27,
};
타입 스크립트에서 typeof는 특정 변수 타입을 추론하는 기능을 가진다.
맵드타입
타입을 가져와서 변형할때 사용
type 안에서만 사용가능 interface 불가
객체의 모든 key를 유니언으로 써준다. Key:value 형태
type PartialUser ={
[key in ‘id’|’name’|’age’]?:User[key];
};
조건부 타입
type A = number extends string ? string : number;
infer
type ReturnType<T> = T extends () => infer R ? R : never;
type FuncA = () => string;
type FuncB = () => number;
type A = ReturnType<FuncA>;
// string
type B = ReturnType<FuncB>;
// number
type C = ReturnType<number>;
// 조건식을 만족하는 R추론 불가능
// never
Partial
Exclude<T,U>