Class Employee {
firstName: string;
lastName!: string;
middleName?: string;
}
What is the difference in these 3 different fields of Employee
class?
Live Example
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.
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 [ ].
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.
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.
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:
Class
should be class
; JavaScript and TypeScript are case-sensitive.
You need an initializer on firstName
(or a constructor that assigns to it unconditionally).
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
.
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