Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between TypeScript optional type and type | undefined

I am struggling to understand the difference between having a field defined as string | undefined and string?

Our current code uses type definitions like this one:

class Foo {
  public bar: string | undefined;
}

When running this code through TSLint it will take notice and complain about it:

Consider using '?' syntax to declare this property instead of 'undefined' in its type.

Now the question is will using the ? syntax work exactly the same or are there subtle differences that I am missing?

class Foo {
  public bar?: string;
}

So how we are using the string | undefined type right now is in checks like this one:

if (foo.bar) {..} Will this change?

It seems the typescript documentation goes into depth about optional types but not really into how this behaves in a class context.

like image 381
Tigraine Avatar asked Nov 19 '18 09:11

Tigraine


People also ask

Is Optional same as undefined TypeScript?

Both definitions are exactly the same. If you hover Data1 it the TypeScript Playground, it even expands to the Data2 syntax. It is perfectly fine to use either way, and it's totally up to developer or team preference to decide what they want to choose.

What is optional TypeScript?

In typescript, the optional parameter is defined as a parameter that can be made optional while passing the values when the function is called and the values that are passed when the function is called is printed with no errors but when the functions have declared the parameters that are ending with “?” are marked as ...

Can optional be Null TypeScript?

With optional you can leave the argument out, or pass undefined , BUT NOT null .

How do you handle optional in TypeScript?

You must tell TypeScript if a property is optional. 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.


1 Answers

bar?: string is an optional property, whereas bar: string | undefined is a required one:

interface Foo { 
    bar?: string
}

interface Foo2 {
    bar: string | undefined
}

const foo: Foo = {} // OK
const foo2: Foo2 = {} // error, bar is required
const foo2: Foo2 = {bar: undefined} // OK

Regarding this case:

if (foo.bar) {..}

Both approaches are OK (including that Intellisense works in either way).

like image 183
Nurbol Alpysbayev Avatar answered Sep 21 '22 00:09

Nurbol Alpysbayev