日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

一文帶你了解中Typescript中type與interface的區別

作者:我的名字豌豆 更新時間: 2022-05-10 編程語言

?想繼續深入Ts其他知識點的同學可以關注下往期文章~
??? 一文帶你了解Ts泛型的應用
??? 一文講解Typescript中工具類型

?在我們Ts使用的日常開發中,我們對于type(類型別名)與interface(接口)的使用可能傻傻分不清楚,因為他們的功能還是非常相似的,可以說在大多數情況下type與interface還是等價的,我們可以使用兩種中的任意一種來對我們的項目進行類型定義,那么存在即合理,接下來我們將對type與interface有什么區別來進行講解~

type與interface的相同點

定義對象或者函數的形狀

?首先兩者都可以對基本數據類型與函數進行類型定義,比如:

	interface Test {
	    a: string;
	    b: number;
	    c: boolean;
	    d?: number; // 可選屬性
	    readonly e: string; //只讀屬性
	    [f: string]: any //任意屬性
	}
	
    interface TestFunc {
        (name:string,age:number): void
    }
    
    
	type Test = {
	    a: string;
	    b: number;
	    c: boolean;
	    d?: number; // 可選屬性
	    readonly e: string; //只讀屬性
	    [f: string]: any //任意屬性
	}
    type TestFunc = (name:string,age:number) => void
    

支持擴展/繼承

?首先對于type與interface都是支持繼承的,但是兩者進行繼承的方式不同,interface是通過extends來進行繼承,而type是通過&來實現,并且兩者可以進行相互拓展,也就是interface可以拓展為type,type也可以拓展為interface。示例:

	// interface進行拓展
	interface A {
    	a: string;
	}
	interface B extends A {
	    b: string;
	}
	
	let testObj: B = {
	    a: 's',
	    b: 's'
	}
	// type進行拓展
	type A = {
	    a: string;
	}
	
	type Test2 = A & {
	    b: string;
	}
	
	let testObj: B = {
	    a: 'test',
	    b: 'test'
	}
	
	// interface拓展為type
	type A = {
	    a: string
	}
	
	interface B extends A {
	    b: string;
	}
	
	let testObj: B = {
	    a: 'test',
	    b: 'test'
	}
	// type拓展為interface
	interface A {
	    a: string;
	}
	
	type B = A & {
	    b: string;
	}
	
	let testObj: B = {
	    a: 'test',
	    b: 'test'
	}
	

type與interface的不同點

type的不同點

  • type可以定義基本類型的別名,如 type anotherNumber = number,此時anotherNumber可以代表number類型,也作為其number類型的別名
	type C = number;
	
	let numberC: C = 2;
  • type可以通過typeof操作符來進行定義,比如:type A = typeof B
	let num: number = 1;
	
	type C = typeof num;
  • type可以聲明聯合類型,如 type unionA = B1 | B2
	type C = string | number | null;
	let a: C = '1';
	let b: C = 1;
	let c: C = null;
  • type可以聲明元組類型,如 type tupleA = [B1, B2]
	type C = [string, number];
	
	const cArr: C = ['1', 1];

interface的不同點

  • interface可以被多次定義,并且被多次定義的interface會進行類型合并,而type不可以
	// interface進行重復聲明
	interface A {
	    a: number;
	}
	interface A {
	    b: string;
	}
	// 此時類型為{a:number,b:string}
	let testA: A = {
	    a: 1,
	    b: '1'
	}
	// 使用type進行重復聲明類型
	type B = {
	    a: number;
	}
	// error報錯,標識符重復(重復定義了B類型)
	type B = {
	    b: string;
	}

原文鏈接:https://blog.csdn.net/liu19721018/article/details/124533573

欄目分類
最近更新