定义了一个函数来断言对象字段不能为空,但是不起作用,如何修复它?

huangapple go评论177阅读模式
英文:

Defined a function which asserts object fields are non-nullable but not work, how to fix it?

问题

我在TypeScript中定义了一个函数,像这样:

export function assertsNotNil(
obj: T
): asserts obj is {
[P in keyof T]-?: NonNullable<T[P]>;
} {
const nilFields = Object.entries(obj)
.filter(([key, value]) => isNil(value))
.map(([key]) => key);
if (nilFields.length) {
throw new Error(对象的某些字段为空:${nilFields.join(',')});
}
}


我想要使用它来断言一些类型实际上是非空的,这样我就不需要以后再次检查:

const data: string | null = 1 + 1 === 2 ? "abc" : null;

assertsNotNil({ data });

console.log(data.toUpperCase())


但它并没有像我期望的那样工作:

[![在这里输入图片描述][1]][1]

哪里出了问题,我应该如何修复它?

  [1]: https://i.stack.imgur.com/7uo6m.png
英文:

I defined a function in TypeScript like this:

export function assertsNotNil&lt;T extends object&gt;(
  obj: T
): asserts obj is {
  [P in keyof T]-?: NonNullable&lt;T[P]&gt;;
} {
  const nilFields = Object.entries(obj)
    .filter(([key, value]) =&gt; isNil(value))
    .map(([key]) =&gt; key);
  if (nilFields.length) {
    throw new Error(`Some fields of the object are nil: ${nilFields.join(&#39;,&#39;)}`);
  }
}

I want to use it to assert some types are actually non-nullable so I don't need to check again later:

const data: string | null = 1+1 === 2 ? &quot;abc&quot;: null;

assertsNotNil({data});

console.log(data.toUpperCase())

But it doesn't work as I expected:

定义了一个函数来断言对象字段不能为空,但是不起作用,如何修复它?

Where is wrong and how should I fix it?

答案1

得分: 1

已经通过你的断言检查的事实是,当数据成员通过传递到类型断言函数的对象访问时,编译器会知道:

const data: string | null = 1 + 1 === 2 ? "abc" : null;
const obj = { data };
assertsNotNil(obj);

console.log(data.toUpperCase());      // 错误,'data' 可能为 'null'

console.log(obj.data.toUpperCase());  // 正确

const { data: dataAlias } = obj;
console.log(dataAlias.toUpperCase()); // 正确
英文:

Facts checked by your assertion are known to the compiler when data members are accessed via object passed into the type assertion function:

const data: string | null = 1+1 === 2 ? &quot;abc&quot;: null;
const obj = {data};
assertsNotNil(obj);

console.log(data.toUpperCase());      // ERROR, &#39;data&#39; is possibly &#39;null&#39;

console.log(obj.data.toUpperCase());  // OK

const {data: dataAlias} = obj;
console.log(dataAlias.toUpperCase()); // OK

huangapple
  • 本文由 发表于 2023年6月26日 15:51:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554608.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定