TS-通过
[{name: 1}]
与{ value: T }[]
和T[]
匹配,选择了第一个签名,返回正确的类型T[]
;
// TS example
function transformDataToForm<T>(data: { value: T }[]): T[];
function transformDataToForm<T>(data: T[]): T[];
function transformDataToForm<U, T extends { value?: U }>(data: T[]): (T | U)[] {
return data.map(item => item.value ? item.value : item);
}
const res1: {name: number}[] = transformDataToForm([{name: 1}]);
const res2: number[] = transformDataToForm([{value: 1}]);
流量-错误
我认为流量应该只存在一个匹配的签名。
declare function transformDataToForm<T>(data: { value: T }[]): T[];
declare function transformDataToForm<T>(data: T[]): T[];
function transformDataToForm<U, T: { value?: U }>(data: T[]): (T | U)[] {
return data.map(item => item.value ? item.value : item);
}
const res1: {name: number}[] = transformDataToForm([{name: 1}]);
// ^ Could not decide which case to select. Since case 1 [1] may work but if it doesn't case 2 [2] looks promising too. To fix add a type annotation to inferred union of array element types (alternatively, provide an annotation to summarize the array element type) [3]
// const res2: number[] = transformDataToForm([{value: 1}]);
在Flow中使用函数重载的正确方法是什么?
transformDataToForm
的正确类型是什么?