当前位置:网站首页>Typescript interface and type alias similarities and differences

Typescript interface and type alias similarities and differences

2022-06-11 07:59:00 YY little monster

1. Can describe properties or methods

type MyType = {
    
    name:string;
    say():void;
}
interface MyInterface {
    
    name:string;
    say():void;
}

2. Are allowed to expand

interface MyInterface {
    
    name:string;
    say():void;
}
interface MyInterface2 extends MyInterface{
    
    age:number;
}
let value:MyInterface2 = {
    
    name:'lnj',
    age:18,
    say():void{
    

    }
}

type MyType = {
    
    name:string;
    say():void;
}
type MyType2 = MyType & {
    
    age:number;
}
let value:MyType2 = {
    
    name:'lnj',
    age: 18,
    say():void{
    

    }
}

3.type You can declare basic type aliases , Joint type , Tuples and so on , interface You can't

type MyType1 = boolean;
type MyType2 = string | number;
type MyType3 = [string, boolean, number];

4.type It doesn't merge automatically

interface MyInterface {
    
    name:string
}
interface MyInterface {
    
    age:number
}
let value:MyInterface  ={
    
    name:'lnj',
    age:18
}

type MyType = {
    
    name:string
}
type MyType = {
    
    age:number
}

原网站

版权声明
本文为[YY little monster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110754014330.html