Typescript: Type Anding vs Type Oring

Ashish
3 min readJan 4, 2021

--

Typescript simplifies the code of javascript which makes the code easier to read , write and debug. The most important use case of typescript is static type checking while javascript supports dynamic type checking. This is the reason why developers choose typescript over javascript in popular frameworks and libraries like angular, react etc.

Type Oring :

Have you ever heard this term before ??.. If no then you must it’s one of the hottest interview question asked about typescript 🔥.

The example will tell you the story what I am talking about.

I think you get my point, we have a function name oring which accept the argument whose type may be string or a number , but you can not pass any other type in the function argument ,if you will then it will gives you an error like this….

The oring function will accept both function or a string but not anything other . It’s a kind of functionality which javascript does not provide you can see this type of thing in typescript only, you can also provide more than two type and a user can also use user defined type.

The type {xyz :” ”} is an example of user defined type , you can defined your own type as well in typescript.🤗

Type Anding:

Like type oring , type anding is also one of the useful technique in typescript. But how can we use this operator in typescript , some of you will try by replacing or “ | ” opearator with and “&”operator in above example but you will not get any good results. The most important use case of type Anding is in the interface. Please look at the example below for more clarification.

I define two interface value1 and value2 , the function anding will accept the type of object which will contain the key-value pairs of both value1 and value2 as you can see anding({xyz:2}) will give us an error because we only define value1 key-value pair only in it.

There are various ways through which you can use type Oring and type Anding in typescript.

For more hot topics you can follow me or write in comment box , if you have any uncertainty also describe that in the comment box.

--

--