我正在学习泛型,并使用编译器解决此问题:
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'
我在做什么错了?
答案 0 :(得分:1)
从文档中,只需键入强制返回行即可。
“相信我,我知道我在做什么。”类型断言就像类型强制转换...
https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions
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 <T>array.subarray(0);
}
答案 1 :(得分:1)
没有类型断言的替代解决方案:
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
。