【发布时间】:2020-05-26 19:05:17
【问题描述】:
代理返回条件随机类型。
const numbersArray = [1,2,3,4];
const stringsArray = ['1','2','3','4'];
function func<T>(array: T[]): T[][] {
return [[array[0], array[1]], [array[2], array[3]]];
}
const proxy = () => Math.random() < 0.5 ? numbersArray : stringsArray;
const resulNumbers = func(numbersArray);
const resultStrings = func(stringsArray);
const resultUnion = func(proxy()); // error
错误
const proxy: () => number[] | string[]
Argument of type 'number[] | string[]' is not assignable to parameter of type 'number[]'.
Type 'string[]' is not assignable to type 'number[]'.
Type 'string' is not assignable to type 'number'.(2345)
解决这个问题的正确方法,有什么想法吗?
【问题讨论】:
-
看起来一样,但有另一个用户案例
标签: typescript generics union