Description
Search Terms
named, named types, named return, named tuples, name array
Suggestion
Allow to name types in specific locations, similar to how function parameters or object keys have "names".
Named Return Type
Below is a React higher order component type that suggest user that the return value of the function could be called enhancedComponent
.
type HigherOrderComponent = (component: React.FC) => React.FC; // 😞
type HigherOrderComponent = (component: React.FC) => enhancedComponent: React.FC; // 😎
Named Generic Type
type FetchUser = (id: string) => Promise<User>; // 😞
type FetchUser = (id: string) => Promise<user: User>; // 😎
Named Tuples
Allow to assign names to tuple entries.
type RGB = [number, number, number]; // 😞
type RGB = [r: number, g: number, b: number]; // 😎
Renamed Object Keys
Allow to suggest a better naming for object keys when they are de-structured.
interface Tweet {
_id: string; // 😞
id: number;
}
interface Tweet {
_id: safeId: string; // 😎
id: number;
}
Editors would automatically suggest naming when de-structuring.
const { _id: safeId } = tweet;
Use Cases
- Autocompletion would be able to suggest a good name for a variable.
- From type hints it would be clear not only what the type of something is, but also what it is.
Examples
One could name function return value and parameters using generics.
type StateTransition<State, Args> = (state: State) => (...args: Args) => newState: State;
type IncreaseCounter = StateTransition<number, [increment: number]>;
(Note newState:
and increment:
.)
Currently TypeScript would suggest that parameter is named args_0
. If it could infer the name of the parameter from the Named Tuple above, it would instead suggest increment
.
Also, it is not clear what that last returned number
is. With Named Return this autocompletion dialog could display newState
.
Analogy
When we define a function in TypeScript, we don't skip parameter names like
type Fibonacci = (number) => number;
instead we name the parameters
type Fibonacci = (n: number) => number;
similarly, not just function parameters, but any place where some type is used could be assigned a name
type Fibonacci = (n: number) => result: number;
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.