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.
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.
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 ...
With optional you can leave the argument out, or pass undefined , BUT NOT null .
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.
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).
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