Skip to content

[Suggestion] Mapped types with inner generic arguments and constraints #17375

Closed
@richardspence

Description

@richardspence

Proposal

I'd like to suggest a feature where in mapped types we could unwrap some of the properties. I'm trying to solve a problem where I want to unpromise a type, and this requires access to the inner generic argument type. This is useful in creating redux style reducers that are strongly typed.

Example

//i'd like access to the inner generic arguments, without having to pass TPayload
type Unpromise<TPayload, TPromise extend Promise<TPayload>> = TPayload;

//and then use that also as a type guard for mapped types
type Reducer<TActions> = {
    [K in keyof TActions where TActions[K] extends Promise<any>]: (payload: Unpromise<TActions[K]>)=>void;
    [K in keyof TActions where TActions[K] !extends Promise<any>]: (payload: TActions[K] )=>void;
}

Complete Example

//redux style actions class
class Actions{
    get(): Promise<string>;
}
//redux style reducer
class MyReducer{
  get(payload:string){...}
}

//unpromise type
type Unpromise<TPayload, TPromise extend Promise<TPayload>> = TPayload;

//example derived usage with generic constraints
type Reducer<TActions> = {
    [K in keyof TActions where TActions[K] extends Promise<any>]: (payload: Unpromise<TActions[K]>)=>void;
    [K in keyof TActions where TActions[K] !extends Promise<any>]: (payload: TActions[K] )=>void;
}

//redux style reducer wireup
function handleActions<TActions>(actions: TActions, reducer: Reducer<TActions>){
...
}

//this would check that MyReducer has methods similar to Actions taking in the resolved promise payload as an argument
handleActions(new Actions(), new MyReducer());

related to #12424

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