TypeScript 개념 정리 - 타입 조작하기

dobby·2025년 6월 24일
0

타입스크립트

목록 보기
7/11
post-thumbnail

타입 조작하기

인덱스드 엑세스 타입

인덱스라는 것을 이용해서 다른 타입 내의 특정 프로퍼티의 타입을 추출하는 타입

interface Post {
 title: string;
 content: string;
 author: {
  id: number;
  name: string;
  age: number;
 }
}

// 인덱스트 엑세스 타입
function printAuthorInfo(author: Post['author']) {
 console.log(`${author.name}-${author.id}`); 
}

const post: Post = {
 title: '게시글 제목',
 content: '',
 author: {
  id: 1,
  name: '',
  age: 26,
 }
}
type PostList = {
 title: string;
 content: string;
 author: {
  id: number;
  name: string;
  age: number
 }
}[];

// [name][author] 인덱스의 author 타입을 접근한다.
function printAuthorInfo(author: PostList[number]['author']) {
 console.log(`${author.name}-${author.id}`); 
}

// 하나의 요소의 타입만 가져온다.
const post: PostList[number] = {
 title: '게시글 제목',
 content: '',
 author: {
   id: 1,
   name: '',
   age: 26
 }
}
type Tup = [number, string, boolean];
type Tup0 = Tup[0];
type Tup1 = Tup[1];
type Tup2 = Tup[2];

// 튜플안에 있는 모든 타입의 최적의 공통 타입을 뽑는다.
type TupNum = Tup[number]; // string | number | boolean 

keyof 연산자

특정 객체의 타입으로부터 프로퍼티의 키들을 string 유니온 타입으로 추출하는 연산자

interface Person {
 name: string;
 age: number;
}

// key: "name" | "age"
function getPropertyKey(person: Person, key: keyof Person) {
 return person[key];
}

const person: Person = {
 name: '',
 age: 26,
}

getPropertyKey(person, 'name');
type Person = typeof person;

function getPropertyKey(person: Person, key: keyof typeof person) {
  return person[key];
}

const person: Person = {
 ame: '',
 age: 26
}

getPropertyKey(person, 'name');

mapped type

mapped type은 interface에서는 쓸 수 없고, 타입 별칭에서만 쓸 수 있다.

interface User {
 id: number;
 name: string;
 age: number;
}

type PartialUser = {
 [key in 'id' | 'name' | 'age']?: User[key];
}

type BooleanUser = {
 [key in keyof User]: boolean; 
}

type ReadonlyUser = {
 readonly [key in keyof User]: User[key]; 
}

function fetchUser(): ReadonlyUser {
 // ...
  return {
   id: 1,
   name: '',
   age: 26,
  }
}

function updateUser(user: User) {
  
}

updateUser({
  // id: 1,
  // name: '',
  // age: 26
});

템플릿 리터럴 타입

type Color: 'red ' | 'black' | 'reen';
type Animal = 'dog' | 'cat' | 'chicken';

// type ColoredAnimal = 'red-dog' | 'red-cat' | 'red-chicken' | 'black-dog' ...
type ColoredAnimal = `${Color}-${Animal}`;
profile
성장통을 겪고 있습니다.

0개의 댓글