-
-
Notifications
You must be signed in to change notification settings - Fork 544
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
NonEmptyTuple
type
#476
Comments
I would find it just a bit more readable if it mentioned the word |
I will make the one we already have generic and public. type-fest/source/internal.d.ts Line 74 in fedbc44
|
I agree. Any thoughts on naming it |
Isn't the difference that tuples have a fixed length and arrays have a variable length? So a |
I'm not sure about that, it's more to do with the positioning of the elements and their types. A tuple can have a variable length but an imposed sequence of elements. type VariableLengtTuple1 = [string, boolean, ...number[]];
const foo:VariableLengtTuple1 = ['hello', true, 1, 2, 3]; // Pass
const bar:VariableLengtTuple1 = ['hello', 'world', 1, 2, 3]; // Fail
const baz:VariableLengtTuple1 = ['hello', true, 1, 2, 3, 'not-allowed']; // Fail |
A tuple matches both tuple and array, but array does not match tuple. It's clearer for me to call it a tuple because technically it is one, but I understand that it can be confusing. |
No, a readonly tuple cannot be modified in any ways, a non-readonly tuple can have its members modified as long as they are of the same type. const writableTuple: [string, number]= ['life', 42];
writableTuple[0] = 'hello'; // Pass, it not reaonly
writableTuple[1] = 'hello'; // Fail, Type 'string' is not assignable to type 'number'.
writableTuple[2] = 'hello'; // Fail, key out of bound
const readonlyTuple: readonly [string, number] = ['life', 42];
readonlyTuple[0] = 'hello'; // Fail, Cannot assign to '0' because it is a read-only property. |
Current: Proposed: |
Sadly these ideas won't fly for this use case: type NonEmptyTuple<T extends any = unknown> = readonly [T, ...T[]];
const wontFly: NonEmptyTuple = [...[], ...[1]]; EDIT: At the time of writing, it will fail with:
Using |
Potentially already exists, with the exception that Adam mentions (which I think is just a TypeScript limitation): |
Context: #287
Why add such a simple type? Mostly for readability and discoverability. Most people don't know about this trick and we can document it well with examples and stuff.
Upvote & Fund
The text was updated successfully, but these errors were encountered: