래스 속성은 인터페이스와 동일한 구문을 사용해 선언합니다. 클래스 속성 이름 뒤에는 선택적
으로 타입 애너테이션이 붙습니다.
타입스크립트는 생성자 내의 할당에 대해서 그 멤버가 클래스에 존재하는 멤버인지 추론하려
고 시도하지 않습니다.
다음 예제에서
destination
은
string
으로 명시적으로 선언되어 있어
FieldTrip
클래스 인
스턴스에 할당되고 접근할 수 있습니다. 클래스가
nonexistent
속성을 선언하지 않았기 때문
에 생성자에서
this
.
nonexistent
할당은 허용되지 않습니다.
class FieldTrip {
destination: string;
constructor(destination: string) {
this.destination = destination; // Ok
console.log('We're going to ${this.destination}!');
this.nonexistent = destination;
// ~~~~~~~~~~~// ~~~~~~~~~~~
// Error: Property 'nonexistent' ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.