You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Literal Tuples/'as const' - allow lib creator to mark type parameters as 'as const' to allow for better TS DSLsΒ #59380
The simplest thing that comes to mind, is to be able to use 'as const' in type definition, and have arguments of function using this type have 'as const' modifier active without specifying it on the side of function call
consttest=<TupleextendsArray<any>asconst>(data: Unique<Tuple>)=>{}test([{type: 'Error-Code',value: 100},{type: 'Error-Code',value: 200},// duplicate causes 'never' to be argument type{type: 'Error-Code',value: 200},])
π Motivating Example
Simplified example:
Lets say you are creating DSL/Lib that often uses Tuples with object Literals and you want to make more extensive type checks.
The current solution is to use 'as const' after the argument.
This sadly has some issues:
not really enforceable even though you really want check every single time when the function is used
repeated boilerplate code that uglifies the code quite a bit
really confusing for users that have a little knowledge of TS, and you just wont them to fill in data
It would be great if this responsibility could be optionally redirected to DSL/lib creators, so that Type params that are always meant to be used with Tuples of literal values like object literals, would be marked as such by them.
Following simple example illustrates the problem - I want to check for duplicate entries in sample DSL and must always use 'as const' for proper type checks.
// Checks tuple for duplicates - this will fail to work correctly without 'as const'typeUnique<Tupleextendsany[]>= ...
itwouldbegreatifIcouldspecify'as const'forTupletypeparamconsttest=<TupleextendsArray<any>>(data: Unique<Tuple>)=>{}test([{type: 'Error-Code',value: 100},{type: 'Error-Code',value: 200},// here 'as const' must be specified to work, which is inconvenient]asconst)
π» Use Cases
What do you want to use this for?
DSLs and libs that use tuples as function arguments often
What shortcomings exist with current approaches?
Forcing users of libs/DSLs to write 'as const' every time they want to have more powerful typechecks on tuples with literals/object literals
What workarounds are you using in the meantime?
Using 'as const' is the current workaround
Activity
jcalz commentedon Jul 21, 2024
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html#const-type-parameters
jkavalec commentedon Jul 21, 2024
Thank you, this relatively new feature completely flew under my radar. And no Google/SO related search did show any relevant results