简体   繁体   English

如何将字符串或空值分配给变量 TypeScript

[英]How to assign either a string or null to a variable TypeScript

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.在这里,这些值是硬编码的,我怎样才能使它通用,以便它可以吸收任何新旧东西。

You can check this one你可以检查这个

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

const a: Nullable<MyValue> = null

Just declare a custom type只需声明一个自定义类型

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

let name: names = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM