-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Feature Request: const modifier on type parameters #46937
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
Comments
Duplicate of #30680? |
I mean, itβs a little different, in that you are modifying the type parameter and the other one is modifying the constraint for the type parameter. But given that neither feature exists and both serve the same purpose (to cause inference of function arguments as if they were |
This comes very close declare function foo<T extends Record<string, unknown> | unknown[]>(value: T): Readonly<T>
const a = foo({ a: 1 }) // { readonly a: 1 }
const b = foo([1, '2']) // readonly [1, '2'] But yes I believe the use cases here make this a duplicate |
@RyanCavanaugh I'm seeing |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Suggestion
π Search Terms
const readonly modifier assertion immutable
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
Generic functions in TypeScript automatically infer type parameters by its parameters, which is convenient and intelligent.
Sometimes we want to get a more specific inference (asserting some value a is "constant" or "type immutable"):
However, some functions are designed to do such things, which means users should always add "as const" whenever they call it. Can we just place the constant asserting into function declaration?
π Motivating Example
Alternative:
π» Use Cases
It will be really useful for underlying libraries, such as schema validatation.
playground without suggested syntax
The text was updated successfully, but these errors were encountered: