熊熊出没 发表于 2024-6-24 04:52:26

typescript-- interface

接口

类似于对象类型字面量,接口类型也能够表示恣意的对象类型,但是接口类型能够给对象类型定名以及定义类型参数。接口类型无法表示原始类型。
接口声明只存在于编译阶段,在编译以后的JavaScript中不包含任何接口。
接口声明

示例
interface InterfaceName {
    TypeMember;
    TypeMember;
    ...
}
属性签名

示例
PropertyName: Type;
interface Point {
    x:number;
    y:number;
}
调用签名

示例
(ParameterList): Type
interface ErrorConstructor {
    (message?: string):Error;
}
构造签名

示例
new (ParameterList): Type

interface ErrorConstructor {
    new (message?: string): Error;
}   
方法签名

示例
PropertyName(ParameterList):Type
PropertyName: {(ParamterList): Type}
PropertyName: (ParameterList) => Type
interface Document {
    getElementById(elementId: string): HTMLElement | null;
}
interface A {
    f(x: string):string // 方法签名
}
interface B {
    f: {(x:boolean):string} // 属性签名和对象类型字面量
}
interface C {
    f: (x: boolean) => string; // 属性签名和函数类型字面量
}
const f = 'f'
interface D {
    (x:boolean):string // 方法签名中的属性名可以为可计算属性名
}
索引签名

字符串索引签名的语法

:Type // IndexName必须为属性值
interface A {
    : number
}
一个接口中最多可以定义一个字符串索引签名,字符串索引签名会约束对象类型种种那个所有属性的类型
interface A {
    : number;
    a:number;
    b:0;
    c:1 | 2
}
数值索引签名

: Type; //IndexName必须为数值
interface A {
    : string
}
const obj: A = ['a','b','c']
obj// string
若接口中同时存在字符串索引和数值索引签名,数值索引签名必须能够赋值给字符串索引签名的类型,在JavaScript中,对象的属性名只能是字符串(Symbol),虽然JavaScript也会允许数字等其他值为对象的索引,但是终极会转换为字符串类型。
interface A {
    : number;
    : 0 | 1;
}
//交换字符串索引签名和数值索引签名的类型,则会产生编译错误
interface B {
    : 0 | 1;
    : number //编译错误
}
可选属性与方法

默认环境下,接口中属性签名和方法签名定义的对象属性都是必选的。
interface Foo{
    x: string
    y(): number
}
const a: Foo = {x: 'hi'} // 缺少属性y
const b: Foo = {y(){return 0}} // 缺少属性x
const c: Foo = {
    x: 'hi',
    y() {return 0}   
}
interface Foo{
    x?: string;
    y?: number;
}
假如接口中定义了重在方法,所有重载的方法签名必须同时为必选或者是可选的。
interface Foo{
    a(): void;
    a(x:boolean):boolean;
    b?():void;
    b?(x:boolean):boolean;
}
interface Bar {
    a(): void;
    a?(x:boolean):boolean
    // 编译错误,重载签名必须为全部为必选的或者可选的。
}
只读属性与方法

interface A {
    readonly a: string;
    readonly : string;
    readonly : string;
}
若接口中定义了只读的索引签名,那么接口类型中的所有属性都是只读属性。
interface A {
    readonly : number;
}
const a: A = {x: 0}
假如接口中及定义了只读索引签名,又定义了非只读的属性签名,那么非制度的属性签名定义的属性依然是非制度的,除此之外,所有的属性都是只读的
接口的继承

接口可以继承其他的对象类型。
interface Shape {
    name: string
}
interface Circle extends Shape {
    radius: number
}
一个接口可以同时继承多个接口,父接口名之间使用逗号分隔
interface Style {
    color: string
}
interface Shape {
    name: string
}
interface Circle extends Style, Shape {
    radius: number
}

[*]假如子接口和父接口之间存在着同名的类型成员,那么子接口中的属性成员具有更高的优先级。
[*]假如仅是多个父接口之间存在同名的类型成员,而子接口自己没有该同名类型成员,那么父接口中同名类型成员的类型必须是完全相同的

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: typescript-- interface