Skip to content

Generic constraints to property of type #40627

@amatiasq

Description

@amatiasq

Search Terms

generic constraint property type keyof

Suggestion

To be able to constrain the type of the property of an object using a keyof type.

Use Cases

Code speaks better than me:

function manageArrayProperty<TObj, TKey extends keyof TObj>(obj: TObj, key: TKey) {
  // obj[key] has to extend array
  obj[key].forEach(...);
}

Examples

This requires a generic declaration that doesn't define a type but only a constraint

function manageArrayProperty<
  TObj,
  TKey extends keyof TObj,
  TObj[TKey] extends any[]
>(obj: TObj, key: TKey) {
  // this is fine
  obj[key].forEach(...);
}

Previous attempts

I tried to achieve that in different ways, I can create a type constrained to TObj[TKey] and any[] but that doesn't mean TObj[TKey] extends array.

function manageArrayProperty<
  TObj,
  TKey extends keyof TObj,
  TProp extends TObj[TKey] & any[]
>(obj: TObj, key: TKey) {
  // INVALID: obj[key] can not be an array
  obj[key].forEach(...);
}

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions