Home > other >  TypeScript : How to define a new Type can be undefined also
TypeScript : How to define a new Type can be undefined also

Time:11-11

In my project I am converting a Scala code to a TypeScript Code.

Now in Scala language there is a prefined type called Option. Option means it can be a type or can have undefined also.

In TypeScript we typically write it like this:

var myVar : MyType | undefined = await methodCall(...)

And the methodCall can be something like this:

function methodCall(...) : Promise<MyType | undefined>
{
   ........
   // The body of function
}

So now I am looking for a way in TypeScript to represent this Scala Options in such a way I can define a type something like this:

Problem Statement:

MyTypeOption ... it can be of MyType or undefined

Any suggestion how can I do it in TypeScript code?

So far the code I am doing in usual typeScript way:

var myVar : MyType | undefined = await methodCall(...)

function methodCall(...) : Promise<MyType | undefined>
{
   ........
   // The body of function
}

CodePudding user response:

You can build a helper type that union's an arbitrary type with undefined:

type Option<T> = T | undefined;

const n: number = undefined; // Error: Type 'undefined' is not assignable to type 'number'.

const o: Option<number> = undefined; // Okay

type MyType = string;

type MyTypeOption = Option<MyType>;

async () => {
    var myVar = await methodCall();
    myVar.charAt(0); // Error: Object is possibly 'undefined'.
}

async function methodCall(): Promise<MyTypeOption> {
    return undefined;
}

Playground Link

  • Related