웹 개발/Typescript
optional property in interface
투자유v
2022. 1. 4. 01:00
728x90
// optional property 1
interface Person {
name: string;
age?: number;
}
const hello = (p: Person): void => {
console.log(`안녕하세요. 제 이름은 ${p.name}이고 나이는 ${p.age}입니다.`);
};
const p1: Person = { name: "hyun" };
const p2: Person = { name: "kim", age: 32 };
hello(p1);
hello(p2);
// optional property 2
// indexable type
interface Person1 {
name: string;
age: number;
[index: string]: string | number;
}
const p11: Person1 = {
name: "hyun",
age: 32,
job: "developer",
hobby: "soccer",
};
console.log(p11["job"], p11["hobby"]);
- 인터페이스 정의 시 ?를 붙여 있을 수도 있고, 없을 수도 있는 속성을 정의할 수 있다.
- indexable property를 이용해 이름에 상관없이 특정 타입의 속성을 받을 수 있다.
- name, age 이외에도 string으로 된 속성을 동적으로 받을 수 있다.
- 위 코드에서는 job, hobby를 정의했다.