簡體   English   中英

是否可以在 TypeScript 中定義一組剩余參數?

[英]Is it possible to define a set of rest arguments in TypeScript?

我不知道問題標題是否具有暗示性,但我的問題是,在構造函數中,我有一個休息參數,它必須是對象的鍵,我希望在調用構造函數時,它只允許鍵還沒用。

我不知道這是否可能,但如果是的話,如果有人可以幫助我,我會很高興。

一些代碼來說明我的問題如下:


class MyClass<GenType> {
    // With the Utility Type Partial<?> I achieved the behavior of allowing only the keys
    // that the object type GenType has, but it still allows that the same key can be passed
    // as argument more than once
    constructor(...rest: Array<Partial<keyof GenType>>) {

    // constructor stuff
    }

}

type MyGenericType = {
    key1: string,
    key2: number,
    key3: Array<number>
}

// Here, in the initialization, it allows to insert the same key multiple times, but
// i want it to allow that a key can be passed just once
const myClassObject = new MyClass<MyGenericType>("key1", "key2", "key1");

在我的真實代碼中顯示問題的圖像:

真正的代碼問題

請注意,它允許多次傳遞相同的鍵,並且代碼建議顯示所有對象鍵,我希望它不允許多次使用相同的鍵,並且代碼建議只顯示剩余的鍵

我想要的效果可能嗎? 如果是,我該如何實現?

謝謝! 😊

對於正在尋找類似東西的每個人,在發布的評論中,我認為是的,有可能實現它,但是不,沒有簡單或有效的方法來做到這一點,一些可能性在下面的鏈接中:

可能性 1

可能性 2

感謝所有試圖提供幫助的評論,並希望它可以幫助其他人! 😃

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM