TypeScript類型

TypeScript類型

基礎(chǔ)類型

  • string
  • number
  • boolean

數(shù)組

兩種定義數(shù)組方法:

type[]
Array<type> // 泛型寫法

對(duì)象類型

帶有任何屬性的JavaScript的值都可以看作為對(duì)象。

function printCoord(pt: { x: number; y:number }) {
    console.log("坐標(biāo)X的值為:" + pt.x);
    console.log("坐標(biāo)Y的值為:" + pt.y);
}

聯(lián)合類型

兩個(gè)或兩個(gè)其他類型組成的類型

let id: number | string

類型別名

方便重復(fù)使用聯(lián)合類型。單獨(dú)定義一個(gè)類型,重復(fù)使用。

type Point = {
    x: number;
    y: number;
}

type ID = number | string

type UserInputSanitizedString = string

接口

interface Point {
    x: number;
    y: number;
}
function printCoord(pt: Point) {
    console.log("坐標(biāo)X的值為:" + pt.x);
    console.log("坐標(biāo)Y的值為:" + pt.y);
}

類型別名和接口

幾乎所有可以使用interface接口定義的都可以使用type類型別名來定義。

區(qū)別一:擴(kuò)展方式

擴(kuò)展接口,使用extends關(guān)鍵字:

interface Animal {
    name: string
}

interface Bear extends Animal {
    honey: boolean
}

const bear: Bear = {
    name: 'winie',
    honey: true
}

擴(kuò)展類型別名,使用&符號(hào):

type Animal = {
    name: string
}
type Bear = Animal & {
    honey: boolean
} 

區(qū)別二:添加字段方式

接口添加字段,同時(shí)定義兩個(gè)同名的即可:

interface MyWindow {
    count: number
}
interface MyWindow {
    title: string
}

type方式,類型創(chuàng)建之后就不能更改了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容