Description
Suggestion
π Search Terms
private field type declaration
β Viability 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, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
Make it possible to use private fields in type declarations, like:
type MyType<T> = { a: number; #marker: T };
type GetMarkerType<T> = T extends { #marker: infer TResult } ? TResult : never;
Currently this gives an error saying that private fields can only be used inside classes. It is true that no code can be generated for private fields outside classes, but no code is generated when declaring a type.
π Motivating Example
Sometimes it is nice to add markers to a type that define how the type can be used (PhantomData<T>
in Rust).
In my case, I automatically generate endpoint definition like
getUser = { method: 'GET', path: '/something' } as Endpoint<'GET', UserInfo>;
My definition of Endpoint
currently looks like
type Endpoint<T> = { method: 'GET' | 'POST'; path: string; __markerBody: T }
This works, but the only thing that says that the body is fake is the ugly name. If I could instead write
type Endpoint<T> = { method: 'GET' | 'POST'; path: string; #markerBody: T }
no one could even possibly try to access the marker, and there would be no reason for the editor to ever show it.
This feature could also be used in libraries, where you might want opaque state objects to be passed between methods, like
type StateObject = { #marker: 'opaque' };
function createStateObject(initial: string): StateObject {
return { initial } as StateObject;
}
function getInitialValue(obj: StateObject) {
const realObject = obj as { initial: string };
return realObject.initial;
}