How can I check whether the properties of the object in TypeScript are nullable in a simple way? For example
export default interface UserDto{
ID?:int;
USER_NAME?:string;
FIRST_NAME?:string;
LAST_NAME?:string;
USER_ROLE?:string;
TEAM?:string;
IS_ACTIVE?:Boolean;
CREATE_DATI?:DateTime;
UPDATE_DATI?:DateTime;
PASSWORD?:string;
}
The USER_ROLE property here is nullable. How can I return this to me as nullable or not in an if query
2
Answers
If i understand correctly, you would like to write an
if
statement that check if the property of an object is optionnal (so not necessary undefined, but defined as optionnal in the type declaration)It is not possible, because types doesn’t exists at runtime.
All you can do is to check the value, or hardcode the name of the keys that are optionnal and use that in your condition.
At runtime this is not possible because all types are removed when compiled (See "What is type erasure?").
But you can work with the interface at compile time using Conditional Types to check whether a
UserDto
key is optional or not.TypeScript Playground