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?
The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.
First, if you don't tell TypeScript that a property is optional, it will expect it to be set. Adding ? to the property name on a type, interface, or class definition will mark that property as optional. type Foo = { bar?: number; } const a: Foo = {}; // This is now OK!
Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional. Copied!
To make a single property in a type optional, create a utility type that takes a type and the property name as parameters and constructs a new type with the specific property marked as optional. Copied!
old question, but there's a very clean solution in newer versions of typescript
fn(myVar!);
In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With