TypeScript Type Compatibility

Introduction

1
2
3
4
5
6
7
8
9
interface A {
text: string
}

class B {
text: string
}

let a: A = new B() // no error

At least same member

1
2
3
4
5
6
7
8
9
10
11
interface A {
text: string
}

function foo(obj: { text: string }): string {
return obj.text
}

let obj = { text: "some text", num: 3 }
let a: A = obj // success
foo(obj) // success

Functions

1
2
3
4
5
6
7
8
9
10
11
let a = (a: number) => a
let b = (a: number, b: number) => a + b

b = a // success
a = b // error

let x = () => ({ text: "some text" })
let y = () => ({ text: "some text", num: 3 })

x = y // success
y = x // error

Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Animal {
feet: number

constructor(name: string, numFeet: number) {}
}

class Size {
feet: number

constructor(name: string, numFeet: number) {}
}

let a: Animal
let b: Size

a = b // success
b = a // success

Generics

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface Empty<T> {}

let x: Empty<string>
let y: Empty<number>
x = y // success

interface T<T> {
data: T
}

let x1: T<string>
let x2: T<number>

x1 = x2 // error