[英]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.