728x90
Enum과 string 으로 구성된 객체가 있을때 interface 를 다음과 같이 정의할 수 있다.
enum Fruit {
APPLE = 'APPLE',
BANANA = 'BANANA',
}
interface MyInterface {
A: string;
B: string;
fruit: Fruit;
}
아래와 같은 방식으로 객체를 선언할 수 있다.
import { MyInterface, Fruit } from './MyInterface';
const myObject: MyInterface = {
A: 'Hello',
B: 'World',
fruit: Fruit.APPLE,
};
console.log(myObject);
Builder 패턴을 적용하여 MyInterface 객체 배열을 생성하려면 아래와 같이 하면된다.
// MyInterfaceBuilder.ts
import { MyInterface, Fruit } from './MyInterface';
export class MyInterfaceBuilder {
private instances: MyInterface[] = [];
addInstance(A: string, B: string, fruit: Fruit): MyInterfaceBuilder {
this.instances.push({ A, B, fruit });
return this;
}
build(): MyInterface[] {
return this.instances;
}
}
이 클래스는 MyInterface 객체를 배열에 추가하는 addInstance 메서드와 생성된 배열을 반환하는 build 메서드를 가진다.
아래와 같은 방식으로 객체 배열을 생성할 수 있다.
// main.ts
import { MyInterfaceBuilder } from './MyInterfaceBuilder';
import { Fruit } from './MyInterface';
const builder = new MyInterfaceBuilder();
const myInterfaceArray = builder
.addInstance('Hello', 'World', Fruit.APPLE)
.addInstance('Example', 'String', Fruit.BANANA)
.build();
console.log(myInterfaceArray);
728x90
'JavaScript' 카테고리의 다른 글
Partial<T> 를 활용한 객체 초기화 (0) | 2023.04.12 |
---|---|
[Error] Hydration failed because the initial UI does not match what was rendered on the server, Text content does not match server-rendered HTML - hydration 비활성화 (0) | 2023.04.07 |
useEffect 사용하기 (0) | 2023.04.05 |
Property does not exist on type 'never' typescript error (0) | 2023.04.03 |
Next.JS 라우팅 시 값 못 가져옴 (0) | 2023.04.03 |
댓글