gpt4 book ai didi

typescript :文字类型的用户定义类型保护?

转载 作者:行者123 更新时间:2023-12-04 23:35:59 25 4
gpt4 key购买 nike

注意:我是 typescript 的新手。在发布之前,我阅读了 docs关于高级类型和type guards .此外我还阅读了几个相关的 S.O.问题(例如 user defined type guards [typescript]How to write a user defined type guard for "string" | "literal" | "types"? )

与我的问题最相似的是后面的问题,您可能在文字上有一些自定义类型(在这种情况下 string ,但解决方案也应适用于 number ),例如

type Format = 'JSON' | 'CSV' | 'XML'

在第二个问题中,用户提出了关于 typescript keyof 的解决方案的问题。关键字和 @瑞安卡瓦诺answer通过从 literal 更改类型来解决此问题到 interface并检查接口(interface)的键:
// copy-pasted from answer for convenience
interface McuParams {
foo, bar, baz;
}
function isKeyOfMcuParams(x: string): x is keyof McuParams {
switch (x) {
case 'foo':
case 'bar':
case 'baz':
return true;
default:
return false;
}
}

我的问题特别是是否有一种方法可以使用类型本身进行用户定义的类型保护,例如
const isFormat = (maybe:String|Format): maybe is Format => /* something goes here */

据我所知,以下内容不起作用(仅替换 /* something goes here */ ):
// 1
/*
* As stated in the docs "The right side of the instanceof needs to
* be a constructor function" but we have a literal
*/
maybe instaceof Format

//2
/* As stated in the docs "typename" must be "number",
* "string", "boolean", or "symbol"
*/
typeof maybe === 'format'


//3
/* no idea */
(<Format>maybe)


也是如此@瑞安卡瓦诺的答案唯一可行的解​​决方案?似乎非常冗长...

最佳答案

最好的方法是派生类型 Format来自一个值,比如一个包含所有 Format 的数组文字。有a number of ways to do this .假设您使用的是 TS3.4+,我将展示最简单的方法:

const formats = ['JSON', 'CSV', 'XML'] as const;
type Format = typeof formats[number];

您可以验证 Format和以前一样。现在,有了一个数组,你可以用它来构建一个类型保护:
function isFormat(x: string): x is Format {
// widen formats to string[] so indexOf(x) works
return (formats as readonly string[]).indexOf(x) >= 0;
}

这应该可以按预期工作并且不会太冗长(或者至少它不会在任何地方重复字符串文字)。希望有帮助;祝你好运!

关于 typescript :文字类型的用户定义类型保护?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55850174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com