TypeScript | 객체의 타입

샘샘·2023년 5월 29일
0

TypeScript

목록 보기
6/13
let coordinate: { x: number; y: number } = { x: 34, y: 2 };
function randomCoordinate(): { x: number; y: number } {
  return { x: Math.random(), y: Math.random() };
}

객체의 타입은 패턴을 항상 지정하고 따르게 한다

객체의 프로퍼티 타입

function printName(person: { first: string; last: string }): void {
  console.log(`${person.first} ${person.last}`);
}

printName({ first: "Thomas", last: "Jenkins" });

프로퍼티가 first, lastperson객체를 파라미터로 받는 함수 printName이 있다

printName({ first: "Nick", last: "Jagger", age: 473 });

age는 타입 설정을 해주지 않았기 때문에 사용할 수 없다

const singer = { first: "Nick", last: "Jagger", age: 473 };
printName(singer);

그럴 때는 새로운 변수에 추가하고 싶은 프로퍼티를 넣어서 사용할 수 있다

Type alias

반복되는 타입은 키워드를 정해서 재사용 할 것

맨 앞글자는 대문자를 써야한다

function doublePoint(point: { x: number; y: number }): {
  x: number;
  y: number;
} {
  return { x: point.x * 2, y: point.y * 2 };
}

{ x: number; y: number }가 반복해서 사용되고 있기 때문에 하나의 타입으로 만들어서 사용하는 것이 좋다

type Point = {
  x: number;
  y: number;
};

function doublePoint(point: Point): Point {
  return { x: point.x * 2, y: point.y * 2 };
}

중첩 객체의 애너테이션

마찬가지로 타입을 하나씩 지정해줘야 한다

type Song = {
  title: string;
  artist: string;
  numStreams: number;
  credits: { producer: string; writer: string };
};

Song이라는 중첩 객체의 타입을 만들어서 사용할 수 있다

function calculatePayout(song: Song): number {
  return song.numStreams * 0.0033;
}

function printSong(song: Song): void {
  console.log(`${song.title} - ${song.artist}`);
}

const mySong: Song = {
  title: "Unchained Melody",
  artist: "Tighteous Brothers",
  numStreams: 12873321,
  credits: {
    producer: "Phill Spector",
    writer: "Alex North",
  },
};

calculatePayout(mySong);
printSong(mySong);

선택적 프로퍼티

키 값에 물음표(옵션)을 넣으면 사용을 할 수도, 안 할 수도 있다

type Points = {
  x: number;
  y: number;
  z?: number;
};

const myPoint: Points = { x: 1, y: 3 };

z 프로퍼티를 사용하지 않아도 오류가 발생하지 않는다

readonly 제어자

읽기만 가능하고 재할당이 불가능하다

type User = {
  readonly id: number;
  username: string;
};

const user: User = {
  id: 12345,
  username: "catgirl",
};

console.log(user.id);
user.id = 4234235; // 에러

프로퍼티 앞에 readonly를 붙여주어서 사용한다

교차 타입 (&)

여러개의 타입을 앰퍼샌드(&) 기호로 결합하여 사용한다

type Circle = {
  radius: number;
};

type Colorful = {
  color: string;
};

type ColorfulCircle = Circle & Colorful;

const happyFace: ColorfulCircle = {
  radius: 4,
  color: "yellow",
};

CircleColorful타입을 각각 지정해주고, 새로운 타입인 ColorfulCircle에서 결합을 해주면, 두 타입 모두 사용이 가능하게 된다


type Cat = {
  numLives: number;
};

type Dog = {
  breed: string;
};

type CatDog = Cat & Dog & { age: number; };

const christy: CatDog = {
  numLives: 7,
  breed: "Husky",
  age: 9,
};

CatDog타입을 지정해주고, 새로운 타입인 CatDog에서 결합을 해주는데 age라는 프로퍼티도 추가해서 사용할 수 있다

연습문제

문제 1

Write the Movie type alias to make the following two variables properly typed
Movie라는 타입을 만들어서 dune과 cats 변수에 정의할 것
Make sure that "originalTitle" is optional and "title" is readonly
originalTitle은 선택적 프로퍼티고 title은 읽기 전용으로 할 것

const dune: Movie = {
  title: "Dune",
  originalTitle: "Dune Part One",
  director: "Denis Villeneuve",
  releaseYear: 2021,
  boxOffice: {
    budget: 165000000,
    grossUS: 108327830,
    grossWorldwide: 400671789,
  },
};

const cats: Movie = {
  title: "Cats",
  director: "Tom Hooper",
  releaseYear: 2019,
  boxOffice: {
    budget: 95000000,
    grossUS: 27166770,
    grossWorldwide: 73833348,
  },
};

정답

type Movie = {
  readonly title: string;
  originalTitle?: string;
  director: string;
  releaseYear: number;
  boxOffice: {
    budget: number;
    grossUS: number;
    grossWorldwide: number;
  };
};

문제 2

Write a function called getProfit that accepts a single Movie object
getProfit 함수를 사용해서 앞에서 정의한 Movie 타입의 단일 객체를 불러와서
It should return the movie's worldwide gross minus its budget
해당 영화의 worldwide에서 budget을 뺀 값을 반환해라

정답

function getProfit(movie: Movie): number {
  return movie.boxOffice.grossWorldwide - movie.boxOffice.budget;
}

👇 구조분해할당 했을 때의 답

function getProfit(movie: Movie): number {
  const { grossWorldwide, budget } = movie.boxOffice;
  return grossWorldwide - budget;
}

👇 인라인으로 넣었을 때의 답

function getProfit({ boxOffice: { grossWorldwide, budget } }: Movie): number {
  return grossWorldwide - budget;
}
profile
회계팀 출신 FE개발자 👉콘테크 회사에서 웹개발을 하고 있습니다

0개의 댓글