www.oreilly.com
Classes and Interfaces
- TSはC#からいろいろ借用している
- 実行時はあくまでJSなので、ミックスインのようなJSイディオムもいける
Classes and Inheritance
type Color = 'Black' | 'White'
type File = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H'
type Rank = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
class Game { }
class Position {
constructor(
private file: File,
private rank: Rank
) { }
}
class Piece {
protected position: Position
constructor(
private readonly color: Color,
file: File,
rank: Rank
) {
this.position = new Position(file, rank)
}
}
class King extends Piece { }
class Queen extends Piece { }
class Bishop extends Piece { }
class Knight extends Piece { }
class Rook extends Piece { }
class Pawn extends Piece { }
class Piece {
protected position: Position
constructor(
private readonly color: Color,
file: File,
rank: Rank
) {
}
}
super
class Base {
protected foo() {
}
protected bar = 1
protected get baz() {
return 2
}
}
class Derived extends Base {
constructor() {
super()
super.foo()
super.bar
super.baz
}
}
Using this as a Return Type
class Base {
foo(): Base {
return this;
}
bar(): this {
return this;
}
}
class Derived extends Base {
}
const b = new Base
const bFoo = b.foo()
const bBar = b.bar()
const d = new Derived
const dFoo = d.foo()
const dBar = d.bar()
- PHPのDocコメントでいう
@return $this
にあたるやつ
- newしたものは返せない (
@return static
とは違う)
Interfaces
type Food = {
calories: number
sweet: boolean
tasty: boolean
}
type Sushi = Food & {
salty: boolean
}
type Cake = Food & {
sweet: boolean
}
interface Food {
calories: number
sweet: boolean
tasty: boolean
}
interface Sushi extends Food {
salty: boolean
}
interface Cake extends Food {
sweet: boolean
}
|
type |
interface |
右辺に型の式を書ける |
o |
x. shapeのみ |
シグネチャが合わない交差/継承をすると |
オーバーロード |
エラー |
同一スコープに同一名定義 |
エラー |
declaration merge |
interface A {
good(x: number): string
bad(x: number): string
}
interface B extends A {
good(x: string | number): string
bad(x: string): string
}
type A = {
good(x: number): string
bad(x: number): string
}
type B = A & {
good(x: string | number): string
bad(x: string): string
}
Declaration Merging
interface User {
name: string
}
interface User {
age: number
}
const a: User = {
name: 'John',
age: 20
}
interface User {
age: string
}
interface User {
age: number
}
type User = {
name: string
}
type User = {
age: number
}
const a: User = {
name: 'John',
age: 20
}
type User = {
name: string
}
type User2 = User & {
age: number
}
const a: User2 = {
name: 'John',
age: 20
}
implementations
- classを定義する時にinterfaceを
implements
する
- interfaceでできること・できないこと
Implementing Interfaces Versus Extending Abstract Classes
- interfaceはコンパイル時にのみ存在する
- abstract classはコンパイル後のJSコードに存在する
- 「interfaceでできないこと」はこのことに起因する