Skip to content

【每日学习】2022-01-25 #3

@joys-stack

Description

@joys-stack

typescript 类型声明与接口的区别?

1、类型声明和接口都可以定义类型,但是接口可拓展性比较好,可以通过继承进行拓展,而type声明是通过 & 进行两个类型的结合
2、可以向现有的接口中加入新的字段,相同名字的接口内容会自动合并

`
interface Window {
title: string
}

interface Window {
ts: TypeScriptAPI
}
`

接口函数重载

1、ts中不建议使用接口重载,使用联合类型对函数的参数进行声明
`interface Person {
eat(): void
eat(food: string): string
eat(food: string, coff: string): string
}

interface Man {
work(): void
}

class User implements Person, Man {
constructor(private name: string) {
this.name = name
}

eat(food?: string, coff?: string): string | void {
    // 函数重载实现:根据参数类型执行不同的函数
}

}`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions