15 - Last of Array
type Last<T extends any[]> = [any, ...T][T["length"]];
Does not seem to be working or I am doing something worng here?
https://www.typescriptlang.org/play?#code/C4TwDgpgBAMghgZ2AHgCpQgD2BAdgEwSjlxAG0BdAPigF4oySQAaKAOg9QrNTICIANngDmwABZ8KFANwAoWQGMA9riRQARnABOALliIUSLQEtcwyjXoAWaUA
Great, very neat and clever!
clever... What the fuck , Typescript
You are genius!!!😂
I ended up with the other solution, which uses infer.
I have a question though: why can't we use T[T["length"]]? It gives me an error when I try it =/
I ended up with the other solution, which uses
infer. I have a question though: why can't we useT[T["length"]]? It gives me an error when I try it =/
I guess it's because the length index overflows
I ended up with the other solution, which uses
infer. I have a question though: why can't we useT[T["length"]]? It gives me an error when I try it =/
you need T[T.length-1], so the any is to shift the array once to the right
Does not seem to be working or I am doing something worng here?
https://www.typescriptlang.org/play?#code/C4TwDgpgBAMghgZ2AHgCpQgD2BAdgEwSjlxAG0BdAPigF4oySQAaKAOg9QrNTICIANngDmwABZ8KFANwAoWQGMA9riRQARnABOALliIUSLQEtcwyjXoAWaUA
that's because T["length"] is number since there is no predefined length, and since the first element of [any,...T] is any Last<string[]> is any
Does not seem to be working or I am doing something worng here?
https://www.typescriptlang.org/play?#code/C4TwDgpgBAMghgZ2AHgCpQgD2BAdgEwSjlxAG0BdAPigF4oySQAaKAOg9QrNTICIANngDmwABZ8KFANwAoWQGMA9riRQARnABOALliIUSLQEtcwyjXoAWaUA
type Last<T extends any[]> = [T extends (infer NT)[] ? NT : never, ...T][T["length"]]; should work.
Im inspired me thank you
What about never:
type Last<T extends any[]> = [never, ...T][T["length"]];
type Last<T extends unknown[]> = [unknown, ...T][T["length"]]
this is also working
卧槽 牛逼
type Last<arr extends any[]> = arr extends [...leftProps: any[], infer L] ? L : never
this is also working
type Last<T extends any[]> = T extends [...any, infer L] ? L : T
this is also working
type Last<T extends any[]> = T extends [...infer A, infer B] ? B : never
卧槽 牛逼
nb
type Last<T extends any[]> = T extends [infer F, ...infer R] ? R["length"] extends 0 ? F : Last<R> : never
FYI, subtract operation on types is not natively supported. You can actually find type challenges for this: 2257・MinusOne 7561・Subtract
wow...
You are genius!!!
Think Different
I'm so stupid
type Last<T extends Array<any>> = T extends [T[0]] ? T[0] : (
T extends [T[0], ...infer U] ? Last<U> : never
);