Upon initial inspection, the function below addPropertyIfValueIsNotUndefined
appears to be functioning:
function addPropertyIfValueIsNotUndefined<Value>(key: string, value: Value): { key?: Value; } {
return isNotUndefined(value) ? { [key]: value } : {};
}
function isNotUndefined<TargetValue>(targetValue: TargetValue | undefined): targetValue is TargetValue {
return typeof targetValue !== "undefined";
}
type Test = {
alpha: string;
bravo?: string;
}
const test1: Test = {
alpha: "ALPHA1" ,
// bravo: "BRAVO1"
};
const test2: Test = {
alpha: "ALPHA2",
...addPropertyIfValueIsNotUndefined("bravo", test1.bravo)
};
console.log(test2)
// No errors or warnings from TypeScript compiler or JavaScript VM up to this point
However, what happens when attempting to add a property that is not declared in the Test
type?
I anticipated an error message like
TS2322 Type { gibberish: string; bravo: string | undefined; alpha: string; }' is not assignable to type 'Test'
, but no error or warning is emitted by TypeScript!
const test2: Type = {
alpha: "ALPHA2",
...addPropertyIfValueIsNotUndefined("gibberish", test1.bravo)
};
I believe I understand why this happens. But how can we annotate the return value of addPropertyIfValueIsNotUndefined
? We don't know the key in advance but still need to reference it.