Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript: value type to represent any of the primitive type

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).

like image 491
bsr Avatar asked Mar 18 '14 21:03

bsr


People also ask

What is primitive value in TypeScript?

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.

Are primitive types value 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.

Which of the following primitive types are supported in TypeScript?

TypeScript supports 7 primitive types number , string , boolean , bigint , symbol , undefined , and null . All other data types are objects in Typescript.

How do you know if a value is primitive?

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.


1 Answers

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
}
like image 182
Johan t Hart Avatar answered Nov 15 '22 13:11

Johan t Hart