Skip to content

Make it possible to use private fields in type declarationsΒ #51489

Closed
@erik-kallen

Description

@erik-kallen

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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions