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.
The Partial type in TypeScript is a utility type which does the opposite of Required. It sets all properties in a type to optional.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With