Maybe someone with extended ts knowledge can shed some light on me. I have an object which MAY have some keys - and I want to limit which keys.
In a function I want to initialize a key with a default value (empty array) if it does not exist and then add something to that array.
Typescript keeps complaining the property may be undefined altough thats not logically possible.
Example code:
type keys = "a" | "b" | "c";
let test: {[key in keys]?: string[]} = {};
function add(key: keys, value: any){
test[key] = test[key] || [];
test[key].push(value);
}
test.push is marked by tsc as "object possibly undefined".
This works neither:
function add(key: keys, value: any){
test[key] = test[key] || [];
if(test[key] !== undefined){
test[key].push(value);
}
}
Whatever I do - typescript insists the property might be undefined.
keyis not a single string literal, and the compiler doesn't do control flow by following the identity of a variable, just by narrowing its type; if you want to work around this you should save the known-defined thing to its own variable and use it instead of reindexing, like this. Does that address your question fully or is there something I'm missing?