I have a component in Ember 3.15 where I am trying to do something like
import { action, set } from '@ember/object';
@action
someMethod() {
const value = ... // something random
let propertyName = ... // some variable string
set(this, propertyName, value);
}
It seems to be working fine in the browser but typescript is flagging the set line as an error (specifically the propertyName argument). So if it works, why doesn't typescript like it?
This also seems to be happening with get() where it doesn't like variable propertyNames like get(this, propertyName).
Generally if your property is
@trackedyou dont needsetand can just dothis[propertyName] = value;.However your problem is probably a general typescript limitation. Actual a general problem of static typing:
Typescript does only static analysis. So it does not execute your code. So it can not know is a dynamically generated property key actually exists.
So if you have something like this:
Then typescript will not be able to verify if
this[dynamicProp]actually exists because for this it would need to execute'data' + (1 + 1);so it would know whatdynamicPropactually is. So it is impossible to know ifthis[dynamicProp]exists by static analysis.You can just tell typescript to do what you want by
(this as any)[dynamicProp]and it will just ignore it. But generally if you dynamically compute property keys you can not rely on static analysis.