[TIL] 03.11 데이터 분류, typescript utility type(Partial, Omit, Required, Pick)

2020. 3. 11. 23:46TIL

진행 하던 토이 프로젝트의 데이터들을 어떻게 분류하고 사용할지에 대해서 논의를 나눴다. 간단한 문제라고 생각했는데 생각보다 복잡하였다. 

 

첫 출근을하여 typescript에 대해서 많은것을 알 수 있었다. (공부해야 할 것이 많다....)

 

type 정의 방법

타입으로만 지정을 해줘야 하는줄 알았는데 아래와 같이 스트링으로 지정도 가능하였다. 

interface prop {
	size: "large" | "middle" | "small
}

 

defaultprops

interface props {
	name?: string 
};

const defaultprops: props = {
	name: "John"
};

props의 name 값이 없을 경우 props의 값을 지정해준다. name이 없다면 "Jhon"이 출력이 된다. 

 

Utility type 

자주 사용되는 타입들을 정리해 보았다. 

 

1. Partial : 인터페이스의 모든 프로퍼티를 optional하게 변경한다. 

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

type PartialPerson = Partial<Person>;
const partialPerson: PartialPerson =
{
	name: "John" // name, gender, age를 선택적으로 사용이 가능하다. 
}

 

2. Omit: 사용하지 않을 프로퍼티를 지정한다. 

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

type OmitPerson = Omit<Todo, 'description'>;
const omitPerson: PersonOmit = {
    name: 'John', // description 프로퍼티를 사용하면 안된다. 
    age: 20,
};

 

 

3. Required: 모든 프로퍼티를 받도록 설정한다. 

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

type PartialPerson = Partial<Person>;
type RequiredPerson = Required<PartialPerson>;
const requiredPerson: RequiredPerson = 
{
    name: "John",
    gender: "man",
    age: 20,
}

 

4.Pick : 인터페이스의 프로퍼티중 일부만 받도록 설정한다.

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

type PickPerson = Pick<IPerson, "name" | "age">;
const PickPerson: PartialPerson =
{
    name: "John",  //name, age를 사용해야 한다. gender는 사용하지 못한다. 
    age: 20,
}

 

참고 블로그: https://ithub.tistory.com/239 / 좀더 자세한 설명은 여기로