시작
선택적 프로퍼티 (Optional Properties)
- 변수명 뒤에
?
를 붙여서 인터페이스 사용 시 선택적으로 변수를 사용할 수 있게 해준다.
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
let newSquare = {color: "white", area: 100};
if (config.clor) {
// Error: Property 'clor' does not exist on type 'SquareConfig'
newSquare.color = config.clor;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: "black"});
읽기전용 프로퍼티 (Readonly properties)
- 인터페이스의 변수명 앞에
readonly
를 붙여 수정이 불가능하게 한다.
- const와 같은 역할을 한다. (const는 변수에 사용, readonly는 요소에 사용
interface SquareConfig {
color?: string;
width?: number;
}
함수 타입 (Function Types)
- 인터페이스로 함수의 매개변수 타입을 미리 지정이 가능하다.
- return해주는 값도 인터페이스에서 지정해준 타입과 같아야 한다.
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(src, sub) {
let result = src.search(sub);
return result > -1;
}
클래스 타입 (Class Types) - 인터페이스 구현하기
- Java처럼 클래스에서 인터페이스를 사용할 수 있다.
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
constructor(h: number, m: number) { }
}
다음 포스팅에 이어서...