,
가 아닌 ;
으로 구분한다. let obj: {
key1: type;
key2: type;
}
let poetLater: {
born: number;
name: string;
}
poetLater = {
born: 1935,
name: "Mary Oliver",
}
type Name = {
key1: type;
key2: type;
}
type Poet = {
born: number;
name: string;
}
let poetLater: Poet;
poetLater = {
born: 1935,
name: "Mary Oliver",
}
type WithFirstName = {
firstName: string;
}
type WithLastName = {
lastName: string;
}
const hasBoth = {
firstName: "Lucille",
lastName: "Clifton",
}
let withFirstName: WithFirstName = hasBoth;
let withLastName: WithLastName = hasBoth;
type Color = {
name: string;
id: number;
}
const red: Color = {
name: 'red',
id: 1,
}
// OK
const blue: Color = {
name: 'blue',
}
// Error: Property 'id' is missing in type '{ name: string; }' but required in type 'Color'.
blue 변수에 id 속성이 없어서 에러가 발생했다.
type Color = {
name: string;
id: number;
}
const pink: Color = {
name: 'pink',
id: '2'
}
// Error: Type 'string' is not assignable to type 'number'.
pink 객체의 id 속성이 숫자 타입이 아니라서 에러가 발생했다.
초깃값에 객체 타입에서 정의된 것보다 많은 필드가 있다면 타입 오류가 발생한다.
type Color = {
name: string;
id: number;
}
const orange: Color = {
name: 'orange',
id: 3,
hex: '#fc8403',
}
// Error: Type '{ name: string; id: number; hex: string; }' is not assignable to type 'Color'.
// Object literal may only specify known properties, and 'hex' does not exist in type 'Color'.
hex 속성은 Color 타입에 없기 때문에 에러가 발생한다.
초과 속성 검사는 객체 타입으로 선언된 위치에서 생성되는 객체 리터럴에 대해서만 일어난다. 기존 객체 리터럴을 제공하면 초과 속성 검사를 우회한다.
type Color = {
name: string;
id: number;
}
const orange = {
name: 'orange',
id: 3,
hex: '#fc8403',
}
const hexOrange: Color = orange; // OK
hexOrange 변수는 초깃값이 구조적으로 Color와 일치하기 때문에 타입 오류가 발생하지 않는다.
객체 타입은 중첩시킬 수 있다.
type Student = {
name: {
firstName: string;
lastName: string;
}
age: number;
}
const student1: Student = {
name: {
firstName: 'Sylvia',
lastName: 'Plath',
},
age: 20,
} // OK
const student2: Student = {
name: {
firstName: 'Sylvia',
},
age: 23,
}
// Error: Property 'lastName' is missing in type '{ firstName: string; }' but required in type '{ firstName: string; lastName: string; }'.
중첩된 객체 타입을 작성할 때 중첩되는 객체 속성의 형태를 별칭 객체 타입으로 추출하는 방법도 있다.
👉 타입 오류 메시지에 더 많은 정보를 담을 수 있다.
type Name = {
firstName: string;
lastName: string;
}
type Student = {
name: Name;
age: number;
}
const student1: Student = {
name: {
firstName: 'Sylvia',
lastName: 'Plath',
},
age: 20,
} // OK
:
앞에 ?
를 추가하면 선택적 속성임을 나타낼 수 있다.
type Book = {
pages: number; // 필수 속성(꼭 있어야 함)
author?: string; // author는 선택적 속성(있어도 되고 없어도 됨)
}
const ok: Book = {
pages: 378,
author: 'Rita Dove',
}
// OK
const ok2: Book = {
pages: 378,
}
// OK
const missing: Book = {
author: 'Rita Dove',
}
// Property 'pages' is missing in type '{ author: string; }' but required in type 'Book'.
선택적 속성과 undefined를 포함한 유니언 타입의 속성은 다르다.
type Book = {
pages: number;
author: string | undefined;
}
const ok: Book = {
pages: 378,
author: undefined,
}
// OK
const ok2: Book = {
pages: 378,
}
// Error: Property 'author' is missing in type '{ pages: number; }' but required in type 'Book'.
변수에 여러 객체 타입 중 하나가 될 수 있는 초깃값이 주어지면 타입스크립트는 해당 타입을 객체 타입 유니언으로 유추한다.
const color = Math.random() > 0.5
? { name: 'red', hex: '#fc0303' }
: { name: 'blue', id: 2 };
// 타입:
// {
// name: string;
// hex: string;
// id?: undefined;
// } | {
// name: string;
// id: number;
// hex?: undefined;
// }
// name은 필수, hex와 id는 옵션
type ColorWithHex = {
name: string;
hex: string;
}
type ColorWithId = {
name: string;
id: number;
}
type Color = ColorWithHex | ColorWithId;
const color: Color = Math.random() > 0.5
? { name: 'red', hex: '#fc0303' }
: { name: 'blue', id: 2 };
color.name; // OK
color.id;
// Error: Property 'id' does not exist on type 'Color'.
// Property 'id' does not exist on type 'ColorWithHex'.
in
연산자로 타입을 좁힐 수 있다.
if('id' in color) {
color.id; // OK: color는 ColorWithId로 좁혀짐
} else {
color.hex; // OK: color는 ColorWithHex로 좁혀짐
}
타입스크립트는 if(color.id)
형태로 참 여부를 확인하는 것을 허용하지 않는다. 존재하지 않는 객체 속성에 접근하려고 시도하면 타입 오류로 간주된다.
type ColorWithHex = {
name: string;
hex: string;
type: 'hex';
}
type ColorWithId = {
name: string;
id: number;
type: 'id';
}
type Color = ColorWithHex | ColorWithId;
const color: Color = Math.random() > 0.5
? { name: 'red', hex: '#fc0303', type: 'hex' }
: { name: 'blue', id: 2, type: 'id' };
color.name; // OK
if(color.type === 'id') {
color.id;
}
color.type; // type: "hex" | "id"
&
을 사용해 여러 타입을 동시에 나타낸다. type ArtWork = {
genre: string;
name: string;
}
type Writing = {
pages: number;
name: string;
}
type WrittenArt = ArtWork & Writing;
// 다음과 같음:
// {
// name: string;
// genre: string;
// pages: number;
// }
type ShortPoem = { author: string } & ({ kigo: string; type: 'haiku'; } | { meter: number; type: 'villanelle'; });
// 항상 author 속성을 가짐
// type 속성으로 판별된 유니언 타입
type ShortPoemBase = { author: string };
type Haiku = ShortPoemBase & { kigo: string; type: 'haiku' };
type Villanelle = ShortPoemBase & { meter: number; type: 'villanelle' };
type ShortPoem = Haiku | Villanelle;
type NotPossible = number & string; // type NotPossible = never
let notNumber: NotPossible = 0; // Type 'number' is not assignable to type 'never'.
let notString: NotPossible = ''; // Type 'string' is not assignable to type 'never'.