最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解什么是TypeScript里的Constructor?signature

 更新時(shí)間:2023年07月27日 14:35:08   作者:JerryWang_汪子熙  
這篇文章主要介紹了什么是TypeScript里的Constructor?signature詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

Constructor signature

TypeScript 官方文檔里關(guān)于 Constructor signature 只有這短短的一段話:

JavaScript functions can also be invoked with the new operator. TypeScript refers to these as constructors because they usually create a new object. You can write a construct signature by adding the new keyword in front of a call signature:

JavaScript 函數(shù)也可以使用 new 運(yùn)算符調(diào)用。 TypeScript 將這些稱為構(gòu)造函數(shù),因?yàn)樗鼈兺ǔ?huì)創(chuàng)建一個(gè)新對(duì)象。

編寫構(gòu)造簽名

您可以通過(guò)在調(diào)用簽名前添加 new 關(guān)鍵字來(lái)編寫構(gòu)造簽名:

type SomeConstructor = {
  new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
  return new ctor("hello");
}

但這個(gè)例子還是看得我一頭霧水,自己摸索了一下,寫了一個(gè)例子:

type Jerry = {
    score: number;
}
type SomeConstructor = {
    new(s: number): Jerry;
};
class MyConstructor implements Jerry{
    score: number;
    constructor(score: number){
        this.score = score;
    }
}
function demo(ctor: SomeConstructor, number:number) {
    return new ctor(number);
}
console.log('Ethan:' , demo(MyConstructor, 100));
console.log('Ethan:' , demo(MyConstructor, 200));

定義新的函數(shù)類型

下面的代碼使用 constructor signature 定義了一個(gè)新的函數(shù)類型:

接收的輸入是 number,輸出是自定義類型 Jerry.

如果去掉 new,就是我們已經(jīng)熟悉的 call signature 語(yǔ)法.

class MyConstructor 實(shí)現(xiàn)了 Jerry 類型:

MyConstructor 可以看成 SomeConstructor 的一種具體實(shí)現(xiàn)。

這樣,凡是輸入?yún)?shù)需要傳入 SomeConstructor 的地方,我傳 MyConstructor 進(jìn)去,一樣能夠工作。

demo 在這里相當(dāng)于工廠函數(shù),我們可以看到,盡管應(yīng)用代碼里沒(méi)有顯式使用 new 關(guān)鍵字,最后還是獲得了兩個(gè)不同的實(shí)例:

以上就是詳解什么是TypeScript里的Constructor signature的詳細(xì)內(nèi)容,更多關(guān)于TypeScript Constructor signature的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

广河县| 东安县| 星座| 郸城县| 江华| 南乐县| 汕头市| 本溪| 织金县| 冷水江市| 襄汾县| 永胜县| 正蓝旗| 德昌县| 库尔勒市| 南宁市| 汤阴县| 大方县| 武山县| 六盘水市| 西丰县| 南昌市| 五河县| 同江市| 浏阳市| 梁山县| 友谊县| 建平县| 达日县| 镇安县| 舟曲县| 凌海市| 广饶县| 赫章县| 湖南省| 夏邑县| 防城港市| 临漳县| 台中市| 中卫市| 镇平县|