Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 11, 2022 07:19 pm GMT

A new Typescript primitive

Imagine a variable, whose value can be assigned or removed. How do you check if this variable contains a value?

let value: Value;

You may use undefined or null as placeholders, but what if Value is a generic you don't control, that can be one of these values?

import { Void } from "ts-void";

You can use Void as a new primitive, like null, with the difference that this primitive cannot be provided by users.

let value: Value | Void;

Then you can check if the variable is Void.

if (value !== Void) {  // Now the value is only of type "Value".}

You may also use the NonVoid utility type.

import { type NonVoid } from "ts-void";

And extract the original type from the union.

type Extracted = NonVoid<T | Void>; // equals to T.

You can check ts-void on Github!

black hole

TS-VOID

The eternal void is filled with infinite possibilities ~ Laozi

TypescriptVoidnpm


Original Link: https://dev.to/paolimi/a-new-typescript-primitive-23ac

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To