What is the best way to define a property which can take any of string
,number
and boolean
primitive values. I need a property to accept any of these primitive type as value from an html input field (which can be text/int/bool). having any
miss type safety I was looking for (specifically, it should not be object, function type).
Simple types are also called the primitive types and they belong to built-in predefined types found in TypeScript. The primitive data type is number, string, boolean, null type, and undefined types.
A value type is usually whatever type reside on the Stack . A primitive type is a type defined at the programming language level, often it is even a value type, directly supported by the compiler of the language.
TypeScript supports 7 primitive types number , string , boolean , bigint , symbol , undefined , and null . All other data types are objects in Typescript.
To check a value whether it is primitive or not we use the following approaches: Approach 1: In this approach, we check the type of the value using the typeof operator. If the type of the value is 'object' or 'function' then the value is not primitive otherwise the value is primitive.
Since Typescript 1.4 you can create a union type like this:
type Primitive = string | boolean | number;
And use it like this:
function acceptPrimitive(prim: Primitive) {
// prim is of a primitive type
}
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