Skip to content

Cannot extract/filter property keys from this. #29413

Closed
@superamadeus

Description

@superamadeus

TypeScript Version: 3.3.0-dev.201xxxxx (tested with typescript@next -v: 3.3.0-dev.20190112)

Search Terms: keyof this, mapped this type, filter this properties, filter this property keys

Code

/**
 * Get the property keys of properties on T which are of type U.
 */
type ExtractPropKeysOfType<T, U> = {
  [k in keyof T]: T[k] extends U ? k : never
}[keyof T];

/**
 * Pick the properties on T which are of type U.
 */
type PickPropsOfType<T, U> = Pick<T, ExtractPropKeysOfType<T, U>>;

function pickNumericProps<T>(t: T): PickPropsOfType<T, number> {
  return {} as any;
}

class Example {
  public a!: number;
  public b!: string;
  public c!: 11;

  public ownNumericProps(): PickPropsOfType<this, number> {
    return pickNumericProps(this);
  }

  public consumerMethod(): void {
    type OwnNumericPropKeys = ExtractPropKeysOfType<this, number>; // it seems that TS cannot resolve this type when applied to `this`.

    pickNumericProps(this).a; // ERROR: Property 'a' does not exist on type 'Pick<this, { [k in keyof this]: this[k] extends number ? k : never; }[keyof this]>'.
    this.ownNumericProps().a; // ERROR: Property 'a' does not exist on type 'Pick<this, { [k in keyof this]: this[k] extends number ? k : never; }[keyof this]>'.
  }
}

const example = new Example();
example.ownNumericProps().a; // works as expected
pickNumericProps(example).a; // works as expected

Expected behavior:
The type of pickNumericProps(this) should be { a: number, c: 11 }.

Actual behavior:
The type of pickNumericProps(this) is unresolved (? not sure how to describe it).

Playground Link: Playground link

Related Issues:
Couldn't find any

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions