![](/img/trans.png)
[英]Can I get the property's value as number in a template property decorator in TypeScript?
[英]How can I change the static property field's value in a property decorator in TypeScript?
如果这些属性已被修饰,我想根据某些计算为 static 属性提供一些初始值,所以我制作了这样的代码:
function deco(display?: string) {
// It looks like `any` could work here instead of `T` but I don't want to use `any`
return function <T> (target: T, key: string) {
/*
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)
*/
if (typeof target[key] !== 'number') {
target[key] = 0
}
}
}
class A {
@deco('foo')
static foo : number
@deco('bar')
static bar : number
}
我怎样才能让它工作?
由于您不想使用any
,您可以为工厂(内部)function 尝试这样的事情,使用额外的方法类型参数和类型交集:
return function <T, K extends keyof T> (target: T, key: K) {
if (typeof target[key] !== 'number') {
target[key] = 0 as T[K] & number;
}
}
这段代码的问题在于它假定@deco
只会用于number
类型的属性,否则可能会出现意外行为。 例如,如果您在string
类型的属性上使用此装饰器,它仍会将其值设置为0
。 这是可以接受的,因为 TypeScript 只是 JavaScript 的超集 - 所以是完全有效的 JavaScript - 我们强制设置target[key]
target[key]
T[K]
target[key]
; 允许将target[key]
设置为值)和number
(允许分配数字0
)。 它绕过类型安全。
理想情况下,您将直接在它们的声明中设置初始值,而不是依赖装饰器来填充它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.