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   空白格k  阅读(21)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示