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
, last
인 person객체
를 파라미터로 받는 함수 printName
이 있다
printName({ first: "Nick", last: "Jagger", age: 473 });
age
는 타입 설정을 해주지 않았기 때문에 사용할 수 없다
const singer = { first: "Nick", last: "Jagger", age: 473 };
printName(singer);
그럴 때는 새로운 변수에 추가하고 싶은 프로퍼티를 넣어서 사용할 수 있다
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 프로퍼티를 사용하지 않아도 오류가 발생하지 않는다
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",
};
Circle
과 Colorful
타입을 각각 지정해주고, 새로운 타입인 ColorfulCircle
에서 결합을 해주면, 두 타입 모두 사용이 가능하게 된다
type Cat = {
numLives: number;
};
type Dog = {
breed: string;
};
type CatDog = Cat & Dog & { age: number; };
const christy: CatDog = {
numLives: 7,
breed: "Husky",
age: 9,
};
Cat
과 Dog
타입을 지정해주고, 새로운 타입인 CatDog
에서 결합을 해주는데 age
라는 프로퍼티도 추가해서 사용할 수 있다
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;
};
};
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;
}