Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference Between '!:' and '?:' in TypeScript object definitions?

Class Employee {
  firstName: string;
  lastName!: string;
  middleName?: string;
}

What is the difference in these 3 different fields of Employee class?

Live Example

like image 240
karanraj singh saini Avatar asked Aug 21 '20 12:08

karanraj singh saini


People also ask

What is the difference between object and object in TypeScript?

Object: It describes the functionality, object helps in representing the non-primitive types that is everything except number, string, boolean, big int, symbol, undefined and null. In TypeScript Object(O uppercased) is different from object(o lowercased). Syntax: var y: Object; // This means y has Object interface.

What does !: In TypeScript mean?

It's coercion to a boolean value. Means that you want to make sure your resulting value is either true or false, not undefined or [ ].

How do you define object of objects type in TypeScript?

In TypeScript, object is the type of all non-primitive values (primitive values are undefined , null , booleans, numbers, bigints, strings). With this type, we can't access any properties of a value.

What is difference between unknown and any in TypeScript?

unknown is the type-safe counterpart of any . Anything is assignable to unknown , but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.


1 Answers

The ? in that position marks the property optional.

The ! in that position is the definite assignment assertion. It's sort of a declaration-level version of the non-null assertion operator, but used on a property (can also be used on variables) rather than on an expression.

There are two — or arguably three — errors in that example:

  1. Class should be class; JavaScript and TypeScript are case-sensitive.

  2. You need an initializer on firstName (or a constructor that assigns to it unconditionally).

  3. The ! on lastName tells TypeScript that lastName will definitely be assigned, suppressing the kind of error you're getting for firstName, but nothing (in the example) actually does the assignment that using ! there promises TypeScript you know for sure you're doing.

Edit: The code you linked later deals with #1 and #2 above, but not #3. TypeScript won't warn that lastName is never assigned and assumes its value is a string, when in fact it's not there and so reading its value will result in undefined.

like image 112
3 revs Avatar answered Sep 17 '22 13:09

3 revs