<aside> 📌

객체에 속성에도 옵셔널이나 readonly 수식어가 가능하다.

</aside>

interface Example {
	hello: string;
	world?: number; // Example.world?: number | undefined
	readonly wow: boolean;
	readonly multiple?: symbol;
}

옵셔널인 경우 undefined 타입도 허용된다.

const example: Example = {
	hello: 'hi',
	wow: false,
};

example.no; // Property 'no' does not exist on type 'Example'.
example.wow = true; // Cannot assign to 'wow' because it is a read-only property.

객체를 타이핑할 때 선언하지 않은 속성에 대해서는 에러가 발생한다.

interface Example {
	hello: string;
}

const example: Example = {
	hello: 'hi',
	why: 'error', // 에러 발생 'why' dose not exist in type 'Example'
}
const obj = {
	hello: 'hi',
	why: 'not error', // 에러 발생하지 않음
}

const example2: Example = obj;

1. 인덱스 접근 타입

<aside> 📌 특정 속성에 연동되게 타입을 만들고 싶다면? 인덱스로 타입에 접근하기

</aside>

type Animal = {
	name: string;
}

type N1 = Animal['name']; // string
type N2 = Animal.name // 에러 발생: Cannot access 'Animal.name'

<aside> 📌 속성의 키와 값의 타입이 궁금하다면? typeofkeyof 사용하기

</aside>

const obj = {
	name: 'eunji',
	age: 28,
};

type Keys = keyof typeof obj; // type Keys = 'name' | 'age'
type Values = typeof obj[Keys]; // type Values = string | number

배열의 keyof