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
1 Answer
Reset to default 1There'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
版权声明:本文标题:Determine if object property is getter or regular field as TypeScript conditional type - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744773803a2624502.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论