I'm currently working on developing a function that updates a field in an object if the passed-in value differs from the existing one. The code snippet I have so far is
type KnownCountryKeys = "defaultCountry" | "country";
type IHasCountry = {
[key in KnownCountryKeys]: Country;
};
export async function maybeUpdateCountry<THasCountry extends IHasCountry>(
dto: THasCountry,
countryKey: KnownCountryKeys,
newCountryCode: string
) {
// Pseudo-Code
// I want TypeScript to verify that `dto[countryKey]` matches the Country type.
if (dto[countryKey].code != newCountryCode) {
const newCountry = //...validateCountry
dto[countryCode] = newCountry;
}
}
One drawback of this method is that dto
is limited to the fields specified in KnownCountryKeys
, resulting in error ts2345
. Attempting to make the type more flexible by using an interface leads to error ts2464
. Moreover, I aim to eliminate the need for KnownCountryKeys
as it raises concerns.
The goal is for this function to handle objects of any shape, validate a string key as a Country
type field, and determine whether the country requires updating in a completely type-safe manner.