[英]Check if a string is included in a readonly string array in TypeScript
const ReadOnlyStrings = ['a', 'b', 'c'] as const;
const fn = (key: string)=>{
ReadOnlyStrings.includes(key);
}
Errors in code:代码中的错误:
Argument of type 'string' is not assignable to parameter of type '"a" | 'string' 类型的参数不能分配给 '"a" 类型的参数 | "b" |
"b" | "c"'.
“C”'。
How to advoids the error?如何避免错误?
ReadOnlyStrings
isn't just a readonly array of strings, it's a readonly tuple that says, in its type, that it contains exactly "a"
in the first element, "b"
in the second, and "c"
in the third. ReadOnlyStrings
不仅仅是一个只读字符串数组,它是一个只读元组,它在其类型中表示它在第一个元素中正好包含"a"
,在第二个元素中包含"b"
,在第三个元素中包含"c"
。 From a pure types perspective, it doesn't make sense to ask if it contains any random string;从纯类型的角度来看,询问它是否包含任何随机字符串是没有意义的; you know it contains exactly those strings in exactly that order.
您知道它完全按照该顺序包含那些字符串。 But pragmatically, we sometimes need to do things like that.
但从务实的角度来看,我们有时需要做这样的事情。 :-)
:-)
You can either make it just a readonly array of strings ( playground ):您可以将其设置为只读字符串数组( playground ):
const ReadOnlyStrings: readonly string[] = ["a", "b", "c"] as const;
// ^^^^^^^^^^^^^^^^^^^
const fn = (key: string) => {
console.log(ReadOnlyStrings.includes(key));
};
...or tell TypeScript to treat it as one for just this operation by using a type assertion to widen its type ( playground ): ...或告诉 TypeScript 通过使用类型断言来扩大其类型( 操场)将其视为仅用于此操作的一个:
const ReadOnlyStrings = ["a", "b", "c"] as const;
const fn = (key: string) => {
console.log((ReadOnlyStrings as readonly string[]).includes(key));
// ^ ^^^^^^^^^^^^^^^^^^^^^^
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.