Skip to content

Feature request: get type of object values #29075

@iamawebgeek

Description

@iamawebgeek

Search Terms

getting combined type of object values

Suggestion

I have a case, where I have nested objects and defined types of each key like so:

type One = {
  a: number
  b: string
}
type Two = {
  c: boolean
  d: Function
}
type Root = {
  one: One
  two: Two
}

When I merge/flatten values of object with Root type, I will get something like One & Two. Currently I couldn't find any way to accomplish this with TypeScript types. The only thing I could think of is:

type Flattened = Root[keyof Root]

However, in this case I am getting One | Two which is never, because it searches common inside of One and Two. I wish there is a keyword like valuesof and when I use it, I get combined types of object values.

Use Cases

Would be very useful when setting types for flattened objects. One possible pitfall may be correct way of overriding/merging common props of inner object types.

Examples

function flattenIt<T extends object>(o: T): valuesof T {
  return Object.keys(o).reduce((c, key) => ({ ...current, ...o[key] }), {})
}
type One = {
  a: number
  b: string
}
type Two = {
  c: boolean
  d: Function
}
type Root = {
  one: One
  two: Two
}
const flattened = flattenIt<Root>(someObj)
flattened. // suggests a | b | c | d

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions