简体   繁体   English

将部分接口类型的 object 转换为 TypeScript 中的“完整”接口类型

[英]Convert object of a partial interface type to the "full" interface type in TypeScript

Let's say I have an Interface A that looks like this:假设我有一个如下所示的接口A

interface A {
  prop1: string
  prop2: string
}

I initialize object obj like this:我像这样初始化 object obj

const obj: Partial<A> = { prop1: 'xyz' }

Is there any way to cast obj to A and automatically set any properties not defined in obj but required in A to null or undefined ?有什么方法可以将obj转换为A并自动将obj中未定义但A中需要的任何属性设置为nullundefined I would like to only use partials at the initialization of a variable if possible, and stick to the "full" type in function params.如果可能的话,我只想在变量的初始化时使用局部变量,并在 function 参数中坚持使用“完整”类型。

I cannot change A to be a class.我无法将A更改为 class。

This answer is pretty late, but I'll leave it in case anyone comes across later.这个答案已经很晚了,但我会留下它以防以后有人遇到。

Typescript is all about types, which are used at compile time to check if the code is correct, but removed at runtime to turn code into plain JavaScript. Typescript 是关于类型的,它在编译时用于检查代码是否正确,但在运行时将其删除以将代码转换为纯 JavaScript。 This means, there is no way to add any properties using typescript features.这意味着,无法使用打字稿功能添加任何属性。

However, you can defined a function that takes partial object and sets default properties:但是,您可以定义一个接受部分对象并设置默认属性的函数:

function complete(obj: Partial<A>): A {
  return Object.assign({
    prop1: 'default1',
    prop2: 'default2'
  }, obj);
}

const partial: Partial<A> = { prop1: 'xyz' }
const a: A = complete(partial)
console.log(a) // { prop1: 'xyz', prop2: 'default2' }

If you want to set missing properties to undefined, the same function will work, but you won't be able to cast the returned object to A , because A requires all properties to be strings and not null or undefined如果您想将缺失的属性设置为 undefined,同样的函数将起作用,但您将无法将返回的对象强制转换为A ,因为A要求所有属性都是字符串,而不是nullundefined

As an extension to Alex Chashin's nice answer, here's a variation where the goal is to validate that a Partial<T> is a valid T and safely cast to it, otherwise return undefined.作为 Alex Chashin 的很好回答的扩展,这里有一个变体,其目标是验证Partial<T>是有效的T并安全地转换为它,否则返回未定义。

The obj is passed as the first parameter of Object.assign (target) to maintain referential integrity. obj作为 Object.assign (target) 的第一个参数传递,以保持参照完整性。 The second parameter does a (harmless) merge and satisfies that the result will be a valid T thanks to the if condition.由于 if 条件,第二个参数执行(无害的)合并并满足结果将是有效的T

    interface A {
      value1: string
      value2: string
    }
    
    function validateObject(obj: Partial<A>): A | undefined {
      if (obj.value1 && obj.value2) {
        // Safe cast Partial<T> to T
        return Object.assign(obj, {
          value1: obj.value1,
          value2: obj.value2,
        });
      }
      return undefined;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM