I have a question about typescript optional properties of interfaces. Assuming the following code:
interface Test {
prop1: string;
prop2?: string;
}
function someFunction(data: {prop1: string, prop2: string}) {
console.log(data.prop1 + ": " + data.prop2);
}
function otherFunction(data: Test) {
if (data.prop2) {
someFunction(data); // prop2 might be undefined!
}
}
and having a strict mode set to true.
Typescript gives me the following error:
Argument of type 'Test' is not assignable to parameter of type '{ prop1: string; prop2: string; }'.
Property 'prop2' is optional in type 'Test' but required in type '{ prop1: string; prop2: string; }'.
And the question is: why it is like that? Why doesn't typescript understand this if assertion?
First of all, I'd love to understand why? But also some workaround that does not produce any additional runtime code or some tons of type assertion would be a nice to have if it's possible at all?