检查值对于联合类型是否有效 [英] Checking if a value is valid for a union type

查看:118
本文介绍了检查值对于联合类型是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在应用中定义了这种类型:

Suppose I have this type defined in my app:

type PiiType = 'name' | 'address' | 'email';

我在应用程序周围使用此类型来强制进行一些强类型化.我们可能会从表面上表示PII的服务器上获取信息,并需要根据此类型定义检查PII的类型是否有效.

I use this type around the application to enforce some strong typing. We may get information from the server that ostensibly represents PII, and need to check if the type of the PII is valid or not by this type definition.

关于此问题的先前解决方案建议使用第二个数组复制有效值,并根据内容检查字符串该数组:

A previous solution suggested on this issue suggested having a second array duplicating the valid values, and checking strings against the contents of that array:

type PiiType = 'name' | 'address' | 'email';

isValidPii(value: string): Boolean {
  const piiTypeValues = ['name', 'address', 'email'];
  return piiTypeValues.indexOf(potentialValue) !== -1;
}

这对我们来说是不可取的,因为它需要两次定义类型,删除单个事实来源,并可能导致错误.

This is undesirable for us as it requires defining the type twice, removing a single source of truth and potentially creating errors.

如何在不重复定义的情况下根据此联合类型检查给定值是否有效?

例如,如果有像isoftype这样的运算符,我可以这样使用它:

For example, if there was an operator like isoftype, I could use it like this:

'name' isoftype PiiType;      // true
'hamburger' isoftype PiiType; // false
100 isoftype PiiType;         // false

...但是该运算符不存在,所以我不确定我们应该怎么做才能检查此类型的值是否有效. instanceof存在,但仅检查类/接口,并且typeof仅返回JavaScript类型(例如stringnumber).

... but this operator doesn't exist, so I'm not sure what we should be doing instead to check if a value would be valid for this type. instanceof exists but only checks against classes/interfaces, and typeof only returns the JavaScript type (e.g. string or number).

我们正在考虑使用枚举代替此类型,但我想先检查一下是否可以使用本机类型做些什么.

We're considering using enums instead to represent this typing, but I'd like to check if there's something we can do with a native type instead first.

推荐答案

诀窍是通过一个标识函数来运行数组,该函数可以推断受string约束的元素类型.这将导致编译器推断文字类型的并集:

The trick is to run the array through an identity function that infers an element type constrained by string. That will cause the compiler to infer a union of literal types:

function asLiterals<T extends string>(arr: T[]): T[] { return arr; }
const piiTypeValues = asLiterals(['name', 'address', 'email']);
type PiiType = (typeof piiTypeValues)[number];

此处还有另一种解决方案,但上述方法似乎更简单.

There's another solution here but the above seems a bit simpler.

这篇关于检查值对于联合类型是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆