首页 > 解决方案 > TypeScript - TS2322: Type 'string' is not assignable to type '"str1" | "str2"'

问题描述

I have a function that, can accept only two possible values (for validation). For this I do:

interface PossibleValues {
    key: "str1" | "str2";
}

I can call the function with a string type only. This is by our architectural design and I have to deal with it.

set({key: type})

Because type is string and key can accept only "str1" | "str2" it says: TS2322: Type 'string' is not assignable to type '"str1" | "str2"' which makes sense.

The question is how to overcome this in a most elegant way? I mean I want to pass a string but the function call should fail if the string is not one of the two "str1" | "str2"

What I tried to do is: set({key: type} as PossibleValues) and it stopped complaining but the desired behavior is not achieved. If I pass "str333" for example it still works.

Any ideas?

标签: javascripttypescript

解决方案


您需要意识到 TypeScript 只是为了帮助您解决编译时错误。它对运行时没有任何作用,因为它被编译为 JavaScript。类型和接口不存在。

话虽如此,除非您对字符串进行硬编码以传递给这个函数,否则您str1 | str2不应该依赖 TypeScript 类型来确保它工作。

您需要编写 JavaScript 检查代码并允许将任何字符串传递给函数。

你可以创建一个类型保护来实现这个效果。

https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

function isKey(value: string): value is "str1" | "str2" {
  return value === "str1" || value === "str2";
}

然后,你可以用它告诉 TypeScript 你已经检查了类型。

if(isKey(type)) {
   set({ key: type }); // typescript won't complain anymore because you did a type check
}

推荐阅读