Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GetLength, Tail, LastIndex, and Last #3

Open
fabiancook opened this issue Jul 23, 2019 · 3 comments
Open

Add GetLength, Tail, LastIndex, and Last #3

fabiancook opened this issue Jul 23, 2019 · 3 comments

Comments

@fabiancook
Copy link

fabiancook commented Jul 23, 2019

We're able to get the length of an array using the following:

type GetLength<T extends any[]> = T extends { length: infer L } ? L : never

We can also get everything but the first element of an array using (I did name this Tail, but seems better to be WithoutFirst, or something else):

type WithoutFirst<T extends any[]> = ((...test: T) => void) extends ((sacrifice: any, ...rest: infer R)=>void) ? R : never;

Once we have a length, and a way to tail, then we're able to get the last index of a typed array:

type LastIndex<T extends any[]> = GetLength<T> extends 1 ? 0 : GetLength<WithoutFirst<T>>;

And once we have the last index, we can get the last element

type Last<T extends any[]> = T[LastIndex<T>];

Here is a little demo of it...

http://www.typescriptlang.org/play/#code/C4TwDgpgBA6glsAFgewK7AGJwE4GdgA8AKlBAB7AQB2AJrlAIZUgDaAugHxQC8UAFHwB0wyvgBcUIgEoeXAG7I4NGeUq16A3AwDG2OADM42iBKYgANFGGDsEcVDhV9EbFABKU7hwVKZAfncoCSoIORcAbgAoUEgoAHEIYAAZagBzJAJkPVTHBgAbUgpqOkZmdi5eLLgcqnzCtRKAbyg8tKQJR2dXJKgAXygAnuDQiOjwaCSGfABJWnJieuL6M3KeeMSUqnTEYi5VJagARgGoAAYg9eS2nfgkNEwcfF2OKJiJqcISffVS1k41ogsSYzOZkXZsKKRbTIKj4RjYbAMEASFhUVAAWwARi5LGisTioPg9Fs2GsWIdLAAmSwAIkQEDyeWQNIhkUi+lQVG0wDgMKgNGQAGVkOjEohHKkFt8SitOHwGAikRIiJY8h9ZjRyBJgcANfMiBwZI02b02RyuTy+QLhaKkBLbogdVKij9ZRx5YrkZJVR8AGr5VAmKBOg1Gk1s60isUSj2IixQSlSKKR23iraxpGWADMSagAHo81AAHLIYBQMDIXC4OCY1oRoVRu1bB06jPxhVxliUthJyIp6PNhCOj5tywdpHknvhfOFktlitVmutIA

@joonhocho
Copy link
Owner

@fabiancook isn't typeof length a number? This only works for tuple types not arrays?

@fabiancook
Copy link
Author

I think as long as this is clear within the documentation, it shouldn't be an issue, everything works as I would expect it to, I haven't seen a clear way to get the last/last index of a fixed length array before, so think it would be a great addition to this set of types

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants