[英]How to assign either a string or null to a variable TypeScript
我有一個可以接受字符串或空值的變量,目前我正在定義硬編碼的所有類型值,如下所示
let name : 'Ram' | 'Shyam' | 'Paul' | null = null;
name = customer.name as 'Ram' | 'Shyam' | 'Paul' | null;
在這里,這些值是硬編碼的,我怎樣才能使它通用,以便它可以吸收任何新舊東西。
你可以檢查這個
type MyValue = "A" | "B" | "C"
type Nullable<T> = T | null
const a: Nullable<MyValue> = null
只需聲明一個自定義類型
type names = 'Ram' | 'Shyam' | 'Paul' | null;
let name: names = null;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.