javascript 以类型安全的方式检查对象中的属性

sdnqo3pr  于 2024-01-05  发布在  Java
关注(0)|答案(3)|浏览(127)

代码

  1. const obj = {};
  2. if ('a' in obj) console.log(42);

字符串
不是typescript(没有错误)。我明白为什么会这样了。另外,在TS 2.8.1中,“in”充当类型保护。
但是,有没有一种方法可以检查属性是否存在,但是如果属性没有在obj的接口中定义,则会出错?

  1. interface Obj{
  2. a: any;
  3. }


我不是在说检查未定义的...

ekqde3dh

ekqde3dh1#

您不会得到错误,因为您使用字符串来检查属性是否存在。
你会得到这样的错误:

  1. interface Obj{
  2. a: any;
  3. }
  4. const obj: Obj = { a: "test" };
  5. if (obj.b) // this is not allowed
  6. if ("b" in obj) // no error because you use string

字符串
如果你想对字符串属性进行类型检查,你可以添加index signatures using this example

ukqbszuj

ukqbszuj2#

下面的handle函数检查假设的服务器响应typesafe-way:

  1. /**
  2. * A type guard. Checks if given object x has the key.
  3. */
  4. const has = <K extends string>(
  5. key: K,
  6. x: object,
  7. ): x is { [key in K]: unknown } => (
  8. key in x
  9. );
  10. function handle(response: unknown) {
  11. if (
  12. typeof response !== 'object'
  13. || response == null
  14. || !has('items', response)
  15. || !has('meta', response)
  16. ) {
  17. // TODO: Paste a proper error handling here.
  18. throw new Error('Invalid response!');
  19. }
  20. console.log(response.items);
  21. console.log(response.meta);
  22. }

字符串
Playground Link。函数has可能应该保存在一个单独的实用程序模块中。

展开查看全部
9fkzdhlc

9fkzdhlc3#

您可以在hasOwnProperty周围实现自己的 Package 器函数,它可以进行类型收缩。

  1. function hasOwnProperty<T, K extends PropertyKey>(
  2. obj: T,
  3. prop: K
  4. ): obj is T & Record<K, unknown> {
  5. return Object.prototype.hasOwnProperty.call(obj, prop);
  6. }

字符串
我在这里找到了这个解决方案:TypeScript type narrowing not working when looping
使用方法:

  1. const obj = {
  2. a: "what",
  3. b: "ever"
  4. } as { a: string }
  5. obj.b // Type error: Property 'b' does not exist on type '{ a: string; }'
  6. if (hasOwnProperty(obj, "b")) {
  7. // obj is no longer { a: string } but is now
  8. // of type { a: string } & Record<"b", unknown>
  9. console.log(obj.b)
  10. }


这种方法的局限性是,你只能得到一个记录与单一的关键字添加,你指定。这可能是罚款为某些需要,但如果你需要一个更通用的解决方案,那么我建议像Zod库,可以验证一个复杂的对象,并给你给予完整的类型:https://github.com/colinhacks/zod

展开查看全部

相关问题