gpt4 book ai didi

typescript - 如何检查字符串文字类型是否包含 TypeScript 中的值?

转载 作者:行者123 更新时间:2023-12-02 14:46:55 28 4
gpt4 key购买 nike

我想检查 str 是否在 Name

这可能吗?

/* imagination code */

type Name = 'a1' | 'a2' | .... | 'z100';

function isName(str: string): str is Name {
switch (str) {
case 'a1':
case 'a2':
// ...
case 'z100':
return true;
default:
return false;
}
}

isName('alice') // -> true or false

最佳答案

您不能从类型转到运行时检查。类型在编译时被删除,所以你不能在运行时真正使用它们中的任何信息。但是,您可以采用另一种方式,从值转到类型:

const Name = ['a1', 'a2', 'z100'] as const // array with all values
type Name = typeof Name[number]; // extract the same type as before

function isName(str: string): str is Name {
return Name.indexOf(str as any) !== -1; // simple check
}

isName('alice') // -> true or false

关于typescript - 如何检查字符串文字类型是否包含 TypeScript 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58590882/

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