[英]How can I make a generic function that recursively deserializes JSON with nested datestrings type safe?
[英]How to make type inference work when generic type can be recursively nested
我剛剛開始使用 function 重載。
我定義了以下帶有重載的 function。 但是,當使用 function 時,泛型類型T
並不總是正確推斷。
function arrayWrapper<T>(input: T): T[];
function arrayWrapper<T>(input: T[]): T[];
function arrayWrapper<T>(input: T | T[]): T[] {
if (input instanceof Array) {
return input;
}
return [input];
}
例如,這段代碼
function arrayWrapperExample(): string[] {
return arrayWrapper(['hello']); // Error here
}
產生這個推理錯誤:
Type 'string[][]' is not assignable to type 'string[]'.
Type 'string[]' is not assignable to type 'string'.ts(2322)
但是,如果我明確指定promiseWrapper
的通用類型,錯誤就會解決。
function arrayWrapperExample(): string[] {
return arrayWrapper<string>(['hello']);
}
但這是多余的,因為返回類型已經指定了一次,如function的返回類型。
arrayWrapper
的重載是否可以以不需要再次指定string
的方式聲明?
提前致謝!
第一個與您的參數匹配的重載被采用,所以只需將它們按優先級排序(從最具體到最通用):
function arrayWrapper<T>(input: T[]): T[];
function arrayWrapper<T>(input: T): T[];
function arrayWrapper<T>(input: T | T[]): T[] {
if (input instanceof Array) {
return input;
}
return [input];
}
function arrayWrapperExample(): string[] {
return arrayWrapper(['hello']); // Error here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.