0

I'm new to Typescript and trying to figure out what the difference between the following 3 types is:

field1?: string | null;
field2?: string;
field3:  string;

Any reference to Typescript docs to help me understand would be helpful.

user4184113
  • 976
  • 2
  • 11
  • 29

2 Answers2

1
interface A { field1?: string | null; }

Here you have a field that can be omitted (or undefined). That is denoted with the ?: notation. And if the field is defined, it must be either, string or null.

// The following are all allowed
const a1: A = { field1: 'abc' } // string
const a2: A = { field1: null } // null
const a3: A = {} // omitted
const a4: A = { field1: undefined } // explicit undefined

interface B { field2?: string; }

This means the field may be omitted or undefined. But if it is defined it must be a string. This means null is not allowed.

const b1: B = { field2: 'abc' } // string
const b2: B = { field2: null } // ERROR: field2 cannot be null
const b3: B = {} // omitted
const b4: B = { field2: undefined } // explicit undefined

interface C { field3: string; }

This means the field must be a string. It may never be omitted.

const c1: C = { field3: 'abc' } // string
const c2: C = { field3: null } // ERROR: field3 cannot be null
const c3: C = {} // ERROR: field3 cannot be omitted
const c4: C = { field3: undefined } // ERROR: field3 cannot be undefined

Playground


Also relevant, a question about the different between null and undefined: What is the difference between null and undefined in JavaScript?

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
0

You can google it by youself. Optional property/parameter. In your example:

field1?: string | null;

optional property field1 of type string or null. Optional means not required and currently undefined. That's no error.

field2?: string;

optional property field2 of type only string

field3:  string;

declared property of type string, but actually now it has undefined, that's error, and field3 has to be implemented in class constructor.

Anton Marinenko
  • 2,749
  • 1
  • 10
  • 16