Skip to content

infer property setter type #62943

@waelbettayeb

Description

@waelbettayeb

🔍 Search Terms

object property setter type set

✅ Viability Checklist

⭐ Suggestion

A naïve attempt looks like this:

type SetterType<T, K extends PropertyKey> =
  T extends {
    set [P in K](v: infer V): void;
  }
    ? V
    : undefined;

However, this is not supported by the type system, and T[K] always resolves to the getter type (CSSStyleDeclaration in this case)

Question

Is there a supported or recommended way to extract setter parameter types ?

📃 Motivating Example

I’m building a library for constructing and configuring HTMLElements in a type-safe way.
In many DOM APIs, properties have different getter and setter types, for example:

// lib.dom.d.ts
interface ElementCSSInlineStyle {
    /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/attributeStyleMap) */
    readonly attributeStyleMap: StylePropertyMap;
    /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/style) */
    get style(): CSSStyleDeclaration;
    set style(cssText: string);
}

In this case:

element.style reads as CSSStyleDeclaration
element.style = ... writes a string

What I want to express

I want to extract setter parameter types from a type, in order to build helper types such as:

type StyleType = SetterType<ElementCSSInlineStyle, "style">;
// expected: string

type ElementSetters = Setters<ElementCSSInlineStyle>;
// expected: { style: string }

This is especially important for:

  • DOM types (HTMLElement, SVGElement, etc.)
  • Custom Elements, where users define their own getters/setters
    (generating a precomputed HTMLElementSetters type from lib.dom.d.ts does not scale to user-defined elements)

The core limitation

TypeScript currently does not allow generic access to accessor declarations (get / set) in conditional or mapped types.

💻 Use Cases

Safe DOM Custom Element setters

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