Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the type of a class property's getter/setter in TypeScript

Tags:

typescript

As TypeScript class properties can have getters and setters of different types since 4.3, I don't know who to get correctly a property's getter and setter's types.

===

As a class property is considered as a variable, I can't distinguish properly if the given property does have a getter nor/and setter and their type (as Parameters<I> and ReturnType<I> can only work on a function/method).

Some ideas of the expected result:

class Foo {
    get bar(): number { /** ... */ }
    set bar(baz: string) { /** ... */ }
}

type GetterOfFooBar = GetterOf<typeof Foo.prototype.bar>; // number
type SetterOfFooBar = SetterOf<typeof Foo.prototype.bar>; // string
class Foo {
    get bar(): number { /** ... */ }
}

type GetterOfFooBar = GetterOf<typeof Foo.prototype.bar>; // number
type SetterOfFooBar = SetterOf<typeof Foo.prototype.bar>; // never
like image 207
Ratibus11 Avatar asked Nov 02 '25 05:11

Ratibus11


1 Answers

Any use of the type system to observe the property type of a variant accessor will result in the type that you read, not the type that you write. Which means GetterOf<T> is easy but SetterOf<T> is impossible.

This doesn't seem to be very well documented. It is mentioned in the discussion of microsoft/TypeScript#53417 at microsoft/TypeScript#53594:

We always pick the read types.

as well as the implementation notes at microsoft/TypeScript#42425:

The type system remains entirely covariant in other operations! This has some effects that may not be immediately apparent: ... Types with variant getters/setters are effectively reduced to their get side when put through mapped types ... The type T[K] still means the read type of K on T

There is a request at microsoft/TypeScript#43729 (ah, now it's microsoft/TypeScript#60162) to allow the setter type to be queried. It's also possible that if the request at microsoft/Typescript#43826 to support variant accessors in mapped types and index signatures is implemented, it will allow the setter type to be isolated and thus queried. But for now this is not part of the language.

like image 109
jcalz Avatar answered Nov 03 '25 20:11

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!