類型的且運(yùn)算
interface A {
name: string;
age: number;
}
interface B {
name: string;
grade: number;
}
let c: A & B = {
name: 'c',
age: 18,
grade: 100
}
類型的或運(yùn)算
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
給已知的類型取個(gè)別名疙筹, 不會(huì)產(chǎn)生新的類型
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'
多態(tài)的 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' // 沒(méi)有很大的限制。只要符合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, 索引訪問(wèn)操作符拾稳。 所以 T[K][]代表數(shù)組里面的類型可能是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' // 不報(bào)錯(cuò)
interface ReadonlyPerson {
readonly name: string;
readonly age: number;
}
// 有時(shí)候并不需要上述操作
type ReadonlyPerson2 = Readonly<Person> // 此時(shí)所有的屬性都是只讀
const person: Readonly<Person> = {
name: 'simon',
age: 18
}
person.name = 'jack' // 報(bào)錯(cuò)
interface Person {
name: string;
age: number;
grade: number;
}
interface Person2 {
name?:string;
age?: number;
grade?: number;
}
// 下面的方法一樣可以實(shí)現(xiàn)
type Person3 = Partial<Person> // 跟上面一樣
可識(shí)別聯(lián)合
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
interface Circle {
kind: "circle";
radius: number;
}
每個(gè)接口都有 kind屬性但有不同的字符串字面量類型吮炕。 kind屬性稱做可辨識(shí)的特征或 標(biāo)簽。 其它的屬性則特定于各個(gè)接口
type Shape = Square | Rectangle | Circle; // 聯(lián)系起來(lái)
下面使用可識(shí)別聯(lián)合
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;
}
}