2

I have a variable which either can take string or null, currently i am defining all the type values hardcoded as below

  let name : 'Ram' | 'Shyam' | 'Paul' | null = null;
  name = customer.name as 'Ram' | 'Shyam' | 'Paul' | null;

Here, the values are hardcoded, how can i make it generic so that it can intake anything old and new both.

2 Answers 2

8

You can check this one

type MyValue = "A" | "B" | "C"
type Nullable<T>  = T | null

const a: Nullable<MyValue> = null
Sign up to request clarification or add additional context in comments.

2 Comments

I like this Nullable approach, surprisingly I have never seen that before.
Thanks @Zer0 I'm happy to share it for everyone :)
4

Just declare a custom type

type names = 'Ram' | 'Shyam' | 'Paul' | null;

let name: names = null;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.