interface personAge {
readonly name: string; // readonly
age?: number; // Optional Properties
}
function logAge(obj: personAge) { //error
console.log(obj.name);
}
let person = {name:'Capt'};
logAge(person);
Optional Properties
- 속성의 끝에 ?를 붙이면 속성 생략 가능, 인터페이스에 속하지 않는 프로퍼티의 사용을 방지하면서, 사용가능한 프로퍼티를 기술할 때 사용한다.
- 객체 안의 몇 개의 프로퍼티만 채워 함수에 전달하는 "option bags"같은 패턴에 유용하다.
readonly
- 처음 생성할 때만 값을 할당하고 이후에는 변경할 수 없는 속성
- 객체를 const로 지정하면 객체의 값은 변경이 가능하다. const 변수는 재할당만 막아주는 것이지 객체 속성을 바꾸는 것까지 관여하지 않는다.
- readonly는 객체의 속성을 변경하지 못하게 막고 객체가 처음 생성될 때만 값 설정이 가능하고 이후 수정이 불가능하다.
- 단, 컴파일시 에러가 발생하는 것이지 변환된 자바스크립트 파일에서는 변경된다.
1) extends로 복사 가능
interface A extends B {
key : type;
}
2) 타입이름 중복선언
interface Animal {
name :string
}
interface Animal {
legs :number
}
interface SearchFunc {
(source: string, subString: string): boolean
}
// 변수로 직접 함수 값이 할당되었기 때문에 인수 타입 생략가능
// TypeScript의 문맥상 타이핑 (contextualtyping)이 인수 타입 추론
let mySearch: SearchFunc
mySearch = function (src, sub) {
let result = src.search(sub);
return result > -1;
}
interface Animal {
makeSound(): void
}
class Dog implements Animal {
makeSound(): void {
console.log("멍멍");
}
}
interface Animal {
makeSound(): void
}
interface Dog extends Animal {
speed: number
}
class Bulldog implements Dog {
speed: number
makeSound(): void {
console.log("멍멍");
}
}
interface Counter {
(start: number): string
interval: number
reset(): void
}
function getCounter(): Counter {
let counter = function (start: number) {} as Counter
counter.interval = 123;
counter.reset = function () {}
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;