gpt4 book ai didi

TypeScript 泛型 TypedArray : TypedArray is not assignable to T

转载 作者:行者123 更新时间:2023-12-04 10:22:24 29 4
gpt4 key购买 nike

我正在学习泛型,并用编译器解决了这个问题:

type FloatArray = Float32Array | Float64Array;
type IntegerArray =
| Int8Array
| Uint8Array
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Uint8ClampedArray;
type TypedArray = FloatArray | IntegerArray;

export function identityArray<T extends TypedArray>(array: T): T {
return array.subarray(0);
}
// Type 'TypedArray' is not assignable to type 'T'

我在这里做错了什么?

最佳答案

没有类型断言的替代解决方案:

type TypedArray = FloatArray | IntegerArray;
type WithSubArray<T extends TypedArray> = { subarray(begin?: number, end?: number): T };

export function identityArray<T extends TypedArray>(array: WithSubArray<T>): T {
return array.subarray(0);
}

const res1 = identityArray(new Int8Array(2)) // Int8Array 👌
const res2 = identityArray(new Float32Array(2)) // Float32Array 👌
const res3 = identityArray([1, 2, 3]) // ✖

T声明为函数返回类型,确保也返回 T正好在函数体中。通过使用 WithSubArray我们可以让编译器清楚, array.subarray返回 T而不是 TypedArray .

TS Playground to try it out

关于TypeScript 泛型 TypedArray : TypedArray is not assignable to T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60793386/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com