簡體   English   中英

調用泛型 function 時的嚴格類型參數

[英]Strict type argument when calling generic function

假設我有這個通用的 function 定義:

function example<T>(...args): Partial<T> {
    ...
}

問題是如何在調用此 function 時強制此 function 的用戶插入類型參數。 例如:

example(...inputArgs);       // compilation error without using specific type.
example<User>(...inputArgs); // no compilation error when using specific type.

您可以通過為類型參數提供默認值,然后使args的類型有條件來實現類似的效果,這樣當未指定T時, args具有不可能的類型。

T不是never時,我在這里為args的類型寫了any[] 您應該將其替換為 rest 參數在您的應用程序中應具有的任何更具體的類型。

function example<T = never>(...args: [T] extends [never] ? [never] : any[]): Partial<T> {
    return {};
}

// error as expected
const test: object = example();
// OK
const test2: object = example<object>();

游樂場鏈接

如果您希望錯誤消息提供更多信息,可以使用此技巧:

function example<T = never>(...args: [T] extends [never] ? [never, 'You must specify the type parameter explicitly'] : any[]): Partial<T> {
    return {};
}

游樂場鏈接

暫無
暫無

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

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