Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell TypeScript that optional property in object exists and is set?

Tags:

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?

like image 684
ktretyak Avatar asked Jan 11 '17 17:01

ktretyak


People also ask

How do you check if a property exists in an object TypeScript?

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.

How do I specify optional properties in TypeScript?

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!

How do I get all properties optional TypeScript?

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!

How do I make my properties optional in TypeScript interface?

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!


1 Answers

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?

like image 172
aacotroneo Avatar answered Oct 10 '22 00:10

aacotroneo