类型的且运算
interface A {
name: string;
age: number;
}
interface B {
name: string;
grade: number;
}
let c: A & B = {
name: 'c',
age: 18,
grade: 100
}
类型的或运算
interface A {
name: string;
age: number;
}
interface B {
name: string;
grade: number;
}
let c: A | B = {
name: 'c',
grade: 100
}
let d: A | B = {
name: 'c',
age: 18
}
let g: A | B = {
name: 'c',
age: 18,
grade: 100
}
类型别名 type
给已知的类型取个别名, 不会产生新的类型
interface A {
name: string;
age: number;
}
interface B {
name: string;
grade: number;
}
type C = A & B
let c: C = {
name: 'c',
age: 18,
grade: 100
}
字面量类型
interface Course {
category: 'task' | 'video'
}
let course: Course = {
category: 'task' // 值只能是task或者 video
}
type Dir = 'east' | 'west' | 'north' | 'south'
let dir:Dir = 'east'
多态的 this类型
class Calc {
public value: number;
constructor(n: number) {
this.value = n
}
addValue(n: number) {
this.value += n
return this // 返回Calc
}
multiply(n: number) {
this.value *= n
return this // 返回Calc
}
}
let c = new Calc(1)
c.addValue(1).addValue(3).multiply(6)
console.log(c.value) // 30
索引类型
interface CalenderOptions {
[k: string]: any
}
let calender = (options: CalenderOptions) => {}
calender({
view: 'Year',
a: '12345' // 没有很大的限制。只要符合CalenderOptions的 k是string值可以是任意类型。
})
function pluck<T, K extends keyof T>(object: T, keys:K[]):T[K][] {
// T - {name: 'simon', age: 18, grade: 100}
// keyof T - 'name' | 'age' | 'grade'
// K extends keyof T - 'name' | 'age' | 'grade'
// T[K] 类型可能是string或者number, 索引访问操作符。 所以 T[K][]代表数组里面的类型可能是string或者number
return keys.map(n => object[n])
}
let pluckObject = pluck({name: 'simon', age: 18, grade: 100}, ['name', 'age'])
console.log(pluckObject)
interface Person {
name: string;
age: number;
grade: number;
}
type X = keyof Person // "name" | "age" | "grade" 字面量类型
Readonly 和 Partial
interface Person {
name: string;
age: number;
}
const person1:Person = {
name: 'simon',
age: 18
}
person1.name = 'jack' // 不报错
interface ReadonlyPerson {
readonly name: string;
readonly age: number;
}
// 有时候并不需要上述操作
type ReadonlyPerson2 = Readonly<Person> // 此时所有的属性都是只读
const person: Readonly<Person> = {
name: 'simon',
age: 18
}
person.name = 'jack' // 报错
interface Person {
name: string;
age: number;
grade: number;
}
interface Person2 {
name?:string;
age?: number;
grade?: number;
}
// 下面的方法一样可以实现
type Person3 = Partial<Person> // 跟上面一样
可识别联合
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
interface Circle {
kind: "circle";
radius: number;
}
每个接口都有 kind属性但有不同的字符串字面量类型。 kind属性称做可辨识的特征或 标签。 其它的属性则特定于各个接口
type Shape = Square | Rectangle | Circle; // 联系起来
下面使用可识别联合
function area(s: Shape) {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
case "circle": return Math.PI * s.radius ** 2;
}
}