admin管理员组

文章数量:1394217

TypeScript can obviously tell whether a property is statically implemented via getter or plain object, since it doesn't allow subclasses to override getters with static properties.

But is it possible to determine this via conditional type? Something like this:

Playground

class Foo {
  readonly x = 1
}

class Bar {
  private readonly _x = 1
  get x() { return this._x }
}

type FooHasStatic = CheckGetter<Foo, 'x'>
type BarHasStatic = CheckGetter<Bar, 'x'>

type CheckGetter<T, K extends keyof T> = T[K] extends IntrinsicGetter ? false : true

TypeScript can obviously tell whether a property is statically implemented via getter or plain object, since it doesn't allow subclasses to override getters with static properties.

But is it possible to determine this via conditional type? Something like this:

Playground

class Foo {
  readonly x = 1
}

class Bar {
  private readonly _x = 1
  get x() { return this._x }
}

type FooHasStatic = CheckGetter<Foo, 'x'>
type BarHasStatic = CheckGetter<Bar, 'x'>

type CheckGetter<T, K extends keyof T> = T[K] extends IntrinsicGetter ? false : true
Share Improve this question asked Mar 11 at 19:57 user29889977user29889977 1532 silver badges8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

There's no way to do that since TS is concerned more with the shape of types rather than their runtime implementation details. Using accessor instead of an own property seems like an extra check without any deep integration with the rest of the structural typing system.

So both the options just give readonly x:

Playground

本文标签: Determine if object property is getter or regular field as TypeScript conditional typeStack Overflow