[英]Is there a way to use assertion functions with complex validations without creating a specific type?
I'm receiving data from api and I'd like to add some validations on front-end and get correct types after that validations, but really specific ones.我正在从 api 接收数据,我想在前端添加一些验证并在验证后获得正确的类型,但确实是特定的类型。 For example, suppose I'm getting
data
with type { keyA?: { property?: string | null | undefined }, keyB?: string | null } | null
例如,假设我正在
data
类型为{ keyA?: { property?: string | null | undefined }, keyB?: string | null } | null
{ keyA?: { property?: string | null | undefined }, keyB?: string | null } | null
{ keyA?: { property?: string | null | undefined }, keyB?: string | null } | null
and I'd like to be sure property
is a non empty string, while keyB
could be null (just to illustrate I don't want to validate every field, it's not a common NonNull~ case). { keyA?: { property?: string | null | undefined }, keyB?: string | null } | null
并且我想确定property
是一个非空字符串,而keyB
可以是 null(只是为了说明我不想验证每个字段,这不是常见的 NonNull~ 情况)。 Is there a way to do it in another function scope (that receives this data) without manually creating a type?有没有办法在另一个函数范围(接收此数据)中执行此操作而无需手动创建类型?
I tried creating a function:我尝试创建一个函数:
function assertData(data: DType): asserts data {
if(!data) throw new Error('no data')
if(!data.keyA) throw new Error('keyA undefined');
if(!data.keyA.property) throw new Error('property undefined');
After calling the function, I can use data (not null value), but the keyA
can be undefined
.调用函数后,我可以使用数据(不是空值),但
keyA
可以是undefined
。 I expected to able to use data.keyA.property
without problems and already typed as string.我希望能够毫无问题地使用
data.keyA.property
并且已经输入为字符串。
You could modify the function to have the following signature:您可以修改该函数以具有以下签名:
function assertData(data: DType): asserts data is DType & {
keyA: { property: string }
} {
if(!data) throw new Error('no data')
if(!data.keyA) throw new Error('keyA undefined');
if(!data.keyA.property) throw new Error('property undefined')
}
We assert that data
is DType
but also that keyA
and keyA.property
are not undefined.我们断言
data
是DType
,而且keyA
和keyA.property
不是未定义的。
declare const a: DType
assertData(a)
a.keyA.property.charAt(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.