我們宣告如下。
type colors = "green" | "blue" | "red";
有沒有一種方法可以根據條件附加到它?
如:
const shouldAppend = // some logic to return true / false.
if (shouldAppend) {
colors.append('yellow'); // invalid syntax
}
這應該將型別更新為以下內容。
colors = "green" | "blue" | "red" | "yellow";
是否可以附加到型別,我該怎么做?
uj5u.com熱心網友回復:
在打字稿中是不可能的。你不能改變型別,但是你可以創建新的:
type Colors = "green" | "blue" | "red";
type NewColors<T extends string> = Colors | T
// Colors | "yellow"
type Result = NewColors<'yellow'>
請記住,打字稿中有兩個范圍:type scope和value/runtime scope. 不允許在runtime scope. 我的意思是,在編譯期間,所有型別都從源代碼中洗掉。
也許你應該嘗試rescript,因為它幾乎可以讓你做你想做的事:
type t = ..
type t = Other
type t =
| Point(float, float)
| Line(float, float, float, float)
它叫Extensible Variant。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409676.html
標籤:
上一篇:基于引數值的打字稿條件擴展
