Gul*_*han 3 casting string-literals typescript
在Typescript中,假设我想调用具有以下签名的函数 -
function foo(param: "TRUE"|"FALSE"|"NONE")
Run Code Online (Sandbox Code Playgroud)
我该怎样做 -
var str = runtimeString()
if(str === "TRUE" | str === "FALSE" | str === "NONE")
foo(str)
Run Code Online (Sandbox Code Playgroud)
或者,明确的价值观是唯一的方式 -
var str = runtimeString()
if(str === "TRUE")
foo("TRUE")
else if(str === "FALSE" )
foo("FALSE")
else if(str === "NONE")
foo("NONE")
Run Code Online (Sandbox Code Playgroud)
如果您确定运行时字符串是有效选项之一,则可以将字符串强制转换为需要字符串文字类型的函数类型。
type Tristate = "TRUE"|"FALSE"|"NONE";
function foo(param: Tristate) {
return "enhanced: " + param;
}
let validInput = "NONE";
foo(validInput as Tristate);
Run Code Online (Sandbox Code Playgroud)
进行转换的另一种方法是像这样预先设置类型:
foo(<Tristate> validInput);
Run Code Online (Sandbox Code Playgroud)
请注意,您会覆盖编译器对运行时字符串中数据的意见。因此,在运行时,可能会出现定义的三个字符串以外的值进入您的foo函数。
我发现最好的方法是创建一个类型保护
type NullableBoolean = "TRUE" | "FALSE" | "NONE";
function foo(param: NullableBoolean)
{
...
}
function isNullableBool(str: string): str is NullableBoolean
{
return str === "TRUE" || str === "FALSE" || str === "NONE"
}
if(isNullableBool(str)) { foo(str); }
Run Code Online (Sandbox Code Playgroud)
这并不理想,因为您必须重复值列表,但您会得到比 Brett 的答案更好的封装。
创建一个字符串文字类型,如下所示:
type NullableBoolean = "TRUE" | "FALSE" | "NONE";
Run Code Online (Sandbox Code Playgroud)
在函数定义中,将此类型用于param:
function foo(param: NullableBoolean)
{
...
}
Run Code Online (Sandbox Code Playgroud)
确保将字符串强制转换为字符串文字类型:
var str = runtimeString();
if(str === "TRUE" || str === "FALSE" || str === "NONE")
foo(<NullableBoolean>str);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3660 次 |
| 最近记录: |