I have the following code:
interface First
{
propertyA: string;
}
// Here propertyA is optional
// Imagine that this interface came from external library.
interface Second
{
propertyA ?: string;
}
function fn(arg: First)
{
// ...
}
// I know that this object can be declared as type of First,
// but I really need set this as type of Second interface
let myVar: Second = {propertyA: 'some string'};
// I really need in this way to make the call.
fn(myVar); // Error
if(myVar.hasOwnProperty('propertyA'))
{
fn(myVar); // Still same error
}
if(myVar.propertyA)
{
fn(myVar); // Still same error
}
But TypeScript throw error:
Argument of type 'Second' is not assignable to parameter of type 'First'. Property 'propertyA' is optional in type 'Second' but required in type 'First'.
So, how to tell TypeScript that optional property propertyA
in myVar
exists and is set?