TypeScript -- 接口和对象类型

75 阅读2分钟

对象的类型

interface定义对象结构

在typescript中,我们定义对象的方式要用关键字interface(接口),我的理解是使用interface来定义一种约束让数据的结构满足约束的格式。定义方式如下:

//这样写是会报错的 因为我们在person定义了a,b但是对象里面缺少b属性
interface Person {
    name:string,
    age:number
}

const person:Person  = {
    name:"213",
    age:15
}

使用接口约束的时候不能多一个属性也不能少一个属性,必须与接口保持一致

interface重名 -- 自动合并

//重名interface  可以合并

interface A{name:string}

interface A{age:number}

let x:A={name:'xx',age:20}

任意属性 [propName: string]、

需要注意的是,一旦定义了任意属性,那么确定属性和可选属性的类型都必须是它的类型的子集

//应为我们定义了[propName: string]: any;
//允许添加新的任意属性
interface Person {
    a:string,
    [propName: string]: any;
}
 
const person:Person  = {
    // a必须校验
    a:"213", 
    
    // c,d,e不会再校验
    c:"123",
    d:123,
    e:[],
}

可选属性 使用?操作符

//可选属性的含义是该属性可以不存在
//所以说这样写也是没问题的
interface Person {
    b?:string,
    a:string
}
 
const person:Person  = {
    a:"213"
}

只读属性 readonly

readonly 只读属性是不允许被赋值的只能读取

//这样写是会报错的
//应为a是只读的不允许重新赋值
interface Person {
    b?: string,
    readonly a: string,
}
 
const person: Person = {
    a: "213",
    c: "123"
}
// 报错
person.a = 123

添加函数

interface Person {
    b?: string,
    readonly a: string,
    [propName: string]: any;
    cb:()=>void
}
 
const person: Person = {
    a: "213",
    c: "123",
    cb:()=>{
        console.log(123)
    }
}

person.cb();
// 报错,不可以更改
person.cb = () => {return 123;}

函数可以调用,不可以更改

继承

//继承 合并属性
interface A{
    name:string
}
 
interface B extends A{
    age:number
}
 
let obj:B = {
    age:18,
    name:"string"
}

约束函数

interface Fn{
    // 参数名为 name,参数类型为String,返回值类型为number数组
    (name:String):number[]
}

const fn:Fn = function(name:string){
    return [1]
}