Closed
Description
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
type LimitedString = string(3);
let limitedString: LimitedString = '1234' // error, LimitedString expects at most 3 characters
limitedString = '12' // would work (or not?)
type LimitedArray = Array(3)<{ something: string }>
let limitedArray: LimitedArray = [{ something: '' }, { something: '' }, { something: '' }, { something: '' }] // error, LimitedArray expects at most 3 members
type LookupStates = {
[index: string(2)]: string
}
// This is useful when you have a normalized array or lookup table, for example
const states: LookupStates = {
'KS': 'Kansas',
'IA': 'Iowa'
}
states['IOWA'] // error