Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

Let's say I have an Interface A that looks like this:

interface A {
  prop1: string
  prop2: string
}

I initialize object obj like this:

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? I would like to only use partials at the initialization of a variable if possible, and stick to the "full" type in function params.

I cannot change A to be a class.

like image 648
Artem Zakharov Avatar asked May 09 '18 20:05

Artem Zakharov


People also ask

What is partial type in TypeScript?

The Partial type in TypeScript is a utility type which does the opposite of Required. It sets all properties in a type to optional.

Can we create object of interface in TypeScript?

To create an object based on an interface, declare the object's type to be the interface, e.g. const obj1: Employee = {} . The object has to conform to the property names and the type of the values in the interface, otherwise the type checker throws an error.

How do I create a new instance of an interface in TypeScript?

TypeScript allows you to specifically type an object using an interface that can be reused by multiple objects. To create an interface, use the interface keyword followed by the interface name and the typed object.

Whats the difference between type and interface in TypeScript?

Interfaces are basically a way to describe data shapes, for example, an object. Type is a definition of a type of data, for example, a union, primitive, intersection, tuple, or any other type.


1 Answers

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.

The obj is passed as the first parameter of Object.assign (target) to maintain referential integrity. The second parameter does a (harmless) merge and satisfies that the result will be a valid T thanks to the if condition.

    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;
    }
like image 109
mtone Avatar answered Sep 19 '22 08:09

mtone