Home > Net >  Do I need to tell TypeScript when a partial is complete, and if so, what's the best way to do t
Do I need to tell TypeScript when a partial is complete, and if so, what's the best way to do t

Time:12-10

I am making an object that initially has only part of the type's required properties, so I am using Partial<Type> to tell TypeScript that's OK.

Later I add the missing property (address). Right now I'm using as to tell TypeScript that the RawAccountWithAddress is complete - i.e. that the type is now RawAccountWithAddress rather than Partial<RawAccountWithAddress>. Using as feels like a hack though.

const rawAccountWithAddress: Partial<RawAccountWithAddress> = ...
rawAccountWithAddress.address = ... 
return rawAccountWithAddress as RawAccountWithAddress;

Is this the best way to tell TypeScript the Partial<Type> is now Type? Shouldn't TypeScript just know that the partial is now complete, since the missing property has been assigned?

Is there a better way of doing this?

For reference the type is:

interface RawAccountWithAddress extends RawAccount {
  address: PublicKey;
}

CodePudding user response:

You're expecting assignment narrowing to apply to the parent object when a property is set, but that doesn't happen, because it would involve synthesizing new object types anytime a property changes, and that would be expensive for the compiler. Still, there is an open issue suggesting this sort of gradual initialization at microsoft/TypeScript#35086, and a more general open issue for narrowing parent objects upon narrowing of their properties at microsoft/TypeScript#42384. If you're interested in seeing this happen you might want to go to those issues and give them a

  • Related