Skip to content

Class satisfies typeΒ #61324

Closed as not planned
Closed as not planned
@sdegutis

Description

@sdegutis

πŸ” Search Terms

class satisfies

βœ… Viability Checklist

⭐ Suggestion

Make the keyword satisfies modify the interface of a class when used after the class header.

πŸ“ƒ Motivating Example

We can add properties at runtime in a way that can statically be known about and well typed.

But currently there's no way to tell TypeScript about these properties. This feature request would solve that:

type PrefixedWith$<T> = T & { [K in keyof T as `$${K & string}`]: T[K] };

class Foo satisfies PrefixedWith$ {

  bar = 1;

  constructor() {
    for (const [key, value] of Object.entries(this)) {
      Object.defineProperty(this, '$' + key, { value });
    }

    this.$bar // now we can use this in constructors
  }

  qux() {
    this.$bar // and methods
  }
  
}

const foo = new Foo();
foo.$bar // and externally

πŸ’» Use Cases

  1. What do you want to use this for?

Telling TypeScript about dynamically generated types known about statically.

  1. What shortcomings exist with current approaches?

You have to wrap the class constructor, and constantly cast this, either in method return value assertions or method this-parameters.

  1. What workarounds are you using in the meantime?

Giving up.

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