-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Description
🔍 Search Terms
object property setter type set
✅ Viability Checklist
- 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, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
⭐ 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