FieldsGetters / Settersimplement ClausesOverriding MethodsType-only Field Declarations — declareNo Static classes
Fields
class GoodGreeter { name: string; constructor() { this.name = "hello"; } }
- FIELD 는 constructor 안에서 초기화 되어야 함
- 만약 constructor 말고 다른 곳에서 field를 초기화 할 거라면 ( 예를들어 아마도 외부 라이브러리가 해당 클래스의 값을 채워넣어 줄 때) definite assignment assertion operator
!
를 사용
class OKGreeter { // Not initialized, but no error name!: string; }
Getters / Setters
class C { _length = 0; get length() { return this._length; } set length(value) { this._length = value; } }
추가 로직 없이 필드 값의 get/set pair를 사용하는 것은 Javascript 에서는 거의 사용하지 않는 형태임. 추가 로직을 넣을 것이 아니라면 public field를 그냥 노출해도 상관없음
implement Clauses
- 기본적인 동작은 크게 다른 것 없지만 주의해야 할 점이 있음
interface Checkable { check(name: string): boolean; } class NameChecker implements Checkable { check(s) { Parameter 's' implicitly has an 'any' type. // Notice no error here return s.toLowercse() === "ok"; } }
- interface를 구현했으니
check
의 type 도string
이어야 할 것 같은데 그것을implements
에서 해주지는 않음
- Parameter s 가 내부적으로는 any type이어야 함
Overriding Methods
class Base { greet() { console.log("Hello, world!"); } } class Derived extends Base { greet(name?: string) { if (name === undefined) { super.greet(); } else { console.log(`Hello, ${name.toUpperCase()}`); } } } const d = new Derived(); d.greet(); d.greet("reader");
class Base { greet() { console.log("Hello, world!"); } } class Derived extends Base { // Make this parameter required greet(name: string) { Property 'greet' in type 'Derived' is not assignable to the same property in base type 'Base'. Type '(name: string) => void' is not assignable to type '() => void'. console.log(`Hello, ${name.toUpperCase()}`); } }
- 하위 클래스는 상위 클래스의 필드, 프로퍼티를 override 할 수 있고 그 signature를 맞춰서 override를 해야 함
- 하위 클래스의 인스턴스를 상위 클래스의 타입으로 할당해서 이용하는 것도 일반적임
// Alias the derived instance through a base class reference const b: Base = d; // No problem b.greet();
Type-only Field Declarations — declare
- 상위 클래스에 존재하는 필드의 타입을 조금 더 정확한 타입으로 다시 선언하고 싶을 때
declare
구문을 이용
interface Animal { dateOfBirth: any; } interface Dog extends Animal { breed: any; } class AnimalHouse { resident: Animal; constructor(animal: Animal) { this.resident = animal; } } class DogHouse extends AnimalHouse { // Does not emit JavaScript code, // only ensures the types are correct declare resident: Dog; constructor(dog: Dog) { super(dog); } }
No Static classes
- static class가 필요한 이유는 그 언어들에서 모든 데이터와 함수가 클래스 안에 있게 하기 때문에 그런 것임. TypeScript 에서는 그러한 강제가 없기에 하나의 인스턴스만 존재하는 클래스는 전형적으로 normal object로 표현이 됨