Skip to content

Allow to use subset of Array values as type #32499

Closed
@ORESoftware

Description

@ORESoftware

Search Terms

array values subset

Suggestion

See use cases.

Use Cases

Allow users to type keys based of an array - but do not force users to put all the keys from the array values, just a subset of the values present in the array.

Examples

Simple example, this does not compile, but I want this to compile:

const Events = <const>[
  'bar',
  'foo',
];

type MyEvents = typeof Events[number];

export interface Disco {
  elmo: {
    [key in MyEvents]: true
  }
}

const x: Disco = {   // compiles
  elmo: {
    bar: true,
    foo: true
  }
};

const y: Disco = {   // does not compile, because key y.elmo.foo is missing
  elmo: {
    bar: true,
  }
};


const z: Disco = {   // does not compile, because key y.elmo.bar is missing
  elmo: {
    foo: true,
  }
};

Barriers

The reason the above does not compile is because my objects do not implement all these keys:

  'foo'
  'bar'

they only implement 1 of them. But I want to tell TS that as long as it's a subset of the above list, that it's fine.

I tried using key in Partial<MyEvents> but that didn't work (even tho it would be nice if it did?)
Partial could work for array values not just objects? idk.

Note this same problem occurs when just using a type instead of an array:

type MyEvents = 'bar' |'foo'

export interface Disco {
  elmo: {
    [key in MyEvents]: true  // still requires elmo to have both foo and bar props
  }
}

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

    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