Repository navigation
Feature Request: strictier array and string using parenthesis modifiers #23617
Description
Activity
j-oliveras commented
on Apr 22, 2018 ContributorMore actionsArray case is already supported:
type LimitedArray = [{ something: string }, { something: string }, { something: string }]; let limitedArray: LimitedArray = [{ something: '' }, { something: '' }, { something: '' }, { something: '' }]
limitedArrayhas an error:Type '[{ something: string; }, { something: string; }, { something: string; }, { something: string; }]' is not assignable to type '[{ something: string; }, { something: string; }, { something: string; }]'. Types of property 'length' are incompatible. Type '4' is not assignable to type '3'.Is not the same the type
string[]and[string](the first is an array without limited length, the second is and array with only one string item).For strings, exists a pull request by Wesley Wigham (@weswigham) experimenting with regex validated strings types: #21044.
Reacted by Paulo Cesarthe only problem with both approaches is that either the regex guard than the tuple type have problems with documentation (and plus the verbosity). what if the array is 30 items long? how to show the "quickinfo" in an IDE for the regex guard type? you won't know the format until you read the typings file...
Do not think we should be mixing strings and arrays, there is really no reason why these scenarios should be combined.
Arrays with fixed length are handled to an extend with tuples since they now have fixed length (see #17765). You can already today have a tuple-like type using
Array. e.g.interface FixedLengthArray<T, L extends number> extends Array<T> { "0": T; length: L; } let limitedArray: FixedLengthArray<E, 3> = [{ something: '' }, { something: '' }, { something: '' }, { something: '' }] // error, 4 is not assignable to 3
Strings should be handled with regex validated strings types: #21044 as noted by Jordi Oliveras Rovira (@j-oliveras).
- addedDuplicateAn existing issue was already createdAn existing issue was already created
on Apr 23, 2018 typescript-bot commented
on May 7, 2018 ContributorMore actionsAutomatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
- locked and limited conversation to collaborators
on Jul 31, 2018
TypeScript Version: 2.7.0-dev.201xxxxx
Search Terms: string, array, length, modifier, strict
Some strictly typed languages can catch string / array overflows on compile time against hard coded values, and might help catching some bugs early on. Usually when creating public APIs, sooner or later, you have to implement a max length for either strings or array items, and while you can catch the error AFTER you've made the request, you would have been able to avoid it at the first place.
This helps with validation libraries as well, such as Joi, that can create highly dynamic object schemas.
Code