typeScript学习-TS类型-接口

typeScript学习

接口:

定义:另一种定义对象类型的类型

接口应用场景:

  1、一些第三方包或者框架底层源码中有大量的接口类型
  2、提供方法的对象类型的参数时使用
  3、为多个同类别的类提供统一的方法和属性声明

如何定义接口:

继承接口:

  新的接口只是在原来接口集成之上增加了一些属性或方法,这是就用接口继承

// 继承
// 宠物
interface Pet {
    name: string,
    love: number,
    health: number,
    toHeallth(): void,
}

//
interface Dog extends Pet {
    strain: string, // 品种
    guradHome(): void,
}

 

可索引签名:

// 可索引签名
interface Product {
    name: string,
    price: number,
    account: number,
    [x: string]: any
}


let p: Product = {
    name: 'zhangsan',
    price: 100,
    account: 10,
    descri1: "ok",
    stockno: 1000,
    [Symbol('stockno1')]: 1000,
    100: 'abc',
    true: 1
}

interface Product2 {
    name: string,
    price: number,
    account: number,
    [x: number]: any
}

let p2: Product2 = {
    name: 'zhangsan',
    price: 100,
    account: 10,
    // descri1: "ok", // 错误
    // stockno: 1000, // 错误
    [Symbol('stockno1')]: 1000,
    100: 'abc',
    // true: 1, // 错误
}


interface Product3 {
    name: string,
    price: number,
    account: number,
    [x: symbol]: any
}

let p3: Product3 = {
    name: 'zhangsan',
    price: 100,
    account: 10,
    // descri1: "ok", // 错误
    // stockno: 1000, // 错误
    [Symbol('stockno1')]: 1000,
    // 100: 'abc', // 错误
    // true: 1, // 错误
}


interface Product4 {
    name: string,
    price: number,
    account: number,
    [x: string]: number | string
    // [x: string]: number // 错误
}

let p4: Product4 = {
    name: 'zhangsan',
    price: 100,
    account: 10,
    // descri1: "ok", // 错误
    // stockno: 1000, // 错误
    [Symbol('stockno1')]: 1000,
    // 100: 'abc', // 错误
    // true: 1, // 错误
}


export { }

 

索引访问类型,索引访问类型的深入扩展

const symid = Symbol("productno")
interface Product {
    [symid]: number | string,
    name: string,
    price: number,
    account: number,
    buy(): void
}

// 重名后合并
interface Product {
    webchat: string
}

type A = Product["buy"]
type B = Product["price" | "name"]
type S = Product[typeof symid]

type Pkeys = keyof Product // "name" | "price" | "account" | "buy" | typeof symid

let pkeys: Pkeys = "account"
// let pkeys2: "name" | "price" | "account" | "buy" | typeof symid = "account"

 

posted on 2023-08-11 09:44  空白格k  阅读(35)  评论(0)    收藏  举报

导航