microsoft / microsoft/TypeScript
Declare generics in type assertion / generic constraint and reuse
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
generic, type assertion, narrowing, constraint, reuse
Suggestion
type Fn<T> = (subject: T) => void
const boolFn = fn as (<T extends boolean>Fn<T>)
// or a less flexible, but easier approach
const boolFn = fn as Fn<T extends boolean>
Today there is no way to do that.
The following does not work:
declare type boolFn<T extends boolean> = Fn<T>
const boolFn = fn
The current workaround is to redeclare or compose the base function:
const boolFn = function <T extends boolean>(subject: T) { return fn(subject) }
This unnecessary increase the size of the code.
Use Cases
There are cases where the functionality of a function only differs in their types.
To provide the best experience in TypeScript,
I would like to create some of the common variations of these function but using the same underlying function to keep the actual code size small.
Here is a simple example in type-plus:
export namespace assertType {
export type Fn<T> = (subject: T) => void
}
export function assertType<T>(subject: T) { return }
assertType.isUndefiend = assertType as assertType.Fn<undefined> // ok
assertType.isBoolean = assertType as (<T extends boolean = boolean>assertType.Fn<T>) // propose
// usage
let subject: boolean | string = ...
assertType.isBoolean<false>(subject)
This proposal allows better reuse of generic types and provide better composability.
It also narrow the gap between the ability to type functions vs variables.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The proposal names no source files, tests, or implementation entry points. Start by locating the compiler handling for type assertions, generic constraints, and callable signatures; done means the proposed examples type-check without changing emitted JavaScript.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100