First look, below function addPropertyIfValueIsNotUndefined
works:
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)
// Neither TypeScript compiler nor JavaScript VM errors until here
But what if try to add some property that does not declare on type Test
?
I am expecting that TypeScript emit the error TS2322 Type { gibberish: string; bravo: string | undefined; alpha: string; }' is not assignable to type 'Test'
, but TypeScript will not emit error or warning!
const test2: Type = {
alpha: "ALPHA2",
...addPropertyIfValueIsNotUndefined("gibberish", test1.bravo)
};
Seems like I understood why. But how to annotate the returning value of addPropertyIfValueIsNotUndefined
? We don't know the key at advance but need refer to it.