问题
I was hoping that if I use the built-in map
function on a tuple of length N in TypeScript then the return type would also be a tuple of length N (perhaps with different type for the elements depending on the function being passed to map
). Instead, the return type is just a standard, variable-length array of whatever type the callback function returns. The tuple's length is lost. I wrote a custom function that does what I want, but I'm wondering if there's a better way that is eluding me. I'm trying to improve my understanding of TypeScript. I included a TypeScript Playground link below the code (with the same code). Thanks for your help!
const nums = [1, 2, 3] as const;
// result1 type is string[]
const result1 = nums.map((num) => num.toString());
// so this won't compile
const result2: [string, string, string] = nums.map((num) => num.toString());
// a type assertion would work, but I'd rather not use one...
const result3 = nums.map((num) => num.toString()) as [string, string, string];
// ...because this also compiles yet the type of result4 doesn't match its value
const result4 = nums.map((num) => num.toString()) as [string, boolean, number, symbol, string, number];
// result5 type is [string, string, string]
const result5 = map(nums, (num) => num.toString());
// custom map function that yields the correct return type when used on a tuple
function map<A extends readonly [...any[]], B>(values: A, func: (value: A[number]) => B): { [K in keyof A]: B } {
return values.map(func) as unknown as { [K in keyof A]: B };
}
See on: TypeScript Playground
回答1:
Please try next:
type A = readonly [1, 2, 3]
const nums: A = [1, 2, 3];
const toStr = <T extends number>(num: T) => num.toString() as `${T}`
const result2 = nums.map(toStr); // ("3" | "1" | "2")[]
I believe this is not the best solution, because you still have ('3'|'2'|'1')[] and not ['1','2','3'], but this is some kind of step forward
I will happy to see other solutions here. Very interesting problem )
Works only with T.S 4.1
UPDATE
There is a possibility to create type what you want:
// https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type/50375286#50375286
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
k: infer I
) => void
? I
: never;
// https://github.com/microsoft/TypeScript/issues/13298#issuecomment-468114901
type UnionToOvlds<U> = UnionToIntersection<
U extends any ? (f: U) => void : never
>;
//https://github.com/microsoft/TypeScript/issues/13298#issuecomment-468114901
type PopUnion<U> = UnionToOvlds<U> extends (a: infer A) => void ? A : never;
// https://stackoverflow.com/questions/53953814/typescript-check-if-a-type-is-a-union#comment-94748994
type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
// https://catchts.com/union-array
type UnionToArray<T, A extends unknown[] = []> = IsUnion<T> extends true
? UnionToArray<Exclude<T, PopUnion<T>>, [PopUnion<T>, ...A]>
: [T, ...A];
const map = <A extends readonly [...any[]]>(values: A) =>
<T,>(func: (value: A[number]) => T) => {
type Mapped<
Arr extends Array<unknown>,
Result extends Array<unknown> = [],
> = Arr extends []
? []
: Arr extends [infer H]
? [...Result, T]
: Arr extends [infer Head, ...infer Tail]
? Mapped<[...Tail], [...Result, T]>
: Readonly<Result>;
return (values.map<T>(func)) as Mapped<UnionToArray<A[number]>>
}
const arr = [1, 2, 3] as const;
type Arr = typeof arr;
const result2 = map([1, 2, 3] as const)<{ elem: Arr[number] }>(elem => ({ elem }));
I don't know why, but declaring type inside function is not the best idea. After that, I was able to make BBQ on my laptop.
Feel free to use Mapped
type util for type castings.
来源:https://stackoverflow.com/questions/64112702/possible-to-use-array-prototype-map-on-tuple-in-typescript-while-preserving-tu