When working with objects of type IBob
, it is important to ensure that all fields required by IBob
are defined. One way to achieve this is by creating the object as a fully formed IBob
instance:
let bob: IBob = Object.assign({
anotherValue: 2,
aFunction : (): number => {
return 3;
}
}, alice);
If you only want to partially initialize the object and have some fields missing, you can use Partial
:
let bob: Partial<IBob> = Object.assign({}, alice);
bob.anotherValue = 2;
bob.aFunction = (): number => {
return 3;
}
While making all fields optional using Partial
may not always be suitable, it is a good option to consider. You can also make just the fields of IBob
optional while keeping the ones from IAlice
mandatory for more advanced typing:
let bob: Partial<Pick<IBob, Exclude<keyof IBob, keyof IAlice>>> & IAlice = Object.assign({}, alice);
bob.anotherValue = 2;
bob.aFunction = (): number => {
return 3;
}
It is crucial to be specific about optional fields, especially under strictNullChecks
, as you will need to explicitly check for null before accessing optional fields. If you choose to proceed with a type assertion, be cautious as it can lead to errors if not done accurately:
let bob: IBob = Object.assign({}, alice) as IBob;
// Or (but only if you are not in a tsx file)
let bob: IBob = <IBob>Object.assign({}, alice);