Skip to content

Make it possible to constrain the property value types of an object to type postMessage() #29941

Closed
@felixfbecker

Description

@felixfbecker

Search Terms

postMessage object value constraint

Suggestion

Currently, it is not possible to define a constraint for the value types an object is allowed to have. Many people think this would work:

type Scalar = string | number | boolean | undefined | null
interface CloneableObject {
  [key: string]: Scalar | CloneableObject
}
function postMessage(message: CloneableObject): void

But it will reject any object that do not define an index signature - which makes sense, because this is the index signature syntax.

Surprisingly, it is also not possible with mapped types when the value is typed with an interface or class:

type CloneableObject = {
  [_ in string | number]: Scalar | CloneableObject
}
interface Foo {
  foo: 123
}
const foo: Foo = { foo: 123 }
const cloneable: CloneableObject = foo // Type 'Foo' is not assignable to type CloneableObject'. Index signature is missing in type 'Foo'.

Interestingly, it is assignable when the type is inferred:

const foo = { foo: 123 } // Inferred type: { foo: number; }
const cloneable: CloneableObject = foo

despite hovers not showing an inferred index signature for foo.

One might also try it with generics, but this doesn't work either:

type CloneableObject<T> = {
  [K in keyof T]: Scalar | CloneableObject<T[K]>
}
function postMessage<T>(message: CloneableObject<T>): void
const foo = { method: () => 123 }
postMessage(foo) // No Error?

Use Cases

postMessage() throws an error at runtime when passing it an object that has a method on it. This error should be caught at compile time. This is even more important when using proxy abstractions that build on top of postMessage(), like comlink, because it can be hard to spot at which point a function accepts only cloneable values through multiple layers of abstraction. This constraint should flow through the type system.

As using webworkers, service workers, worker_threads in Node etc is more popular this is an annoying gap in the type system.

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.

Related

#25176
microsoft/TypeScript-DOM-lib-generator#534
#1897
#28019

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