#how to overwrite type definition for property of an object

26 messages · Page 1 of 1 (latest)

summer hamlet
#

say i've an object which is typed, but one of the properties is just typed object as the server hasn't typed it, i'd like to set the type definition to this.

type appleType = {
  color: string
}

response.apple // coming from typed response is type 'object'

response.apple as appleType

response.apple // this will still be typed as object, what can I do here to type it as appleType?

How do i apply the type appleType to a property of the response. I can't edit where the response type defs are coming through as they're auto generated, I need to overwrite them here

lucid crystal
#

can't

#

!hb declaration merging

warped heartBOT
lucid crystal
#

you may be able to do this though

summer hamlet
#

ah ok, thank you for the steer 👍

lucid crystal
#

well

#

otherwise you'd have to assign it to a different variable

#

and do something like const r2 = response as (Omit<typeof response, "apple"> & { apple: AppleType; })

summer hamlet
#

ah yes i've got this working...

#

// Manually applying type definitions for untyped settings object
interface IBaseProjectInfo extends Omit<BaseProjectInfo, "settings"> {
  settings?: ProjectInfoSettingsType;
}

const getProjectBaseInfo = async (projectHash: string) => {
  const { data } = await PROJECT_SERIES_API.getBaseProjectInfo(projectHash);
  return data as IBaseProjectInfo;
};
#

so extending the good object, omitting the bad key, and extending that with my manual type def, then asserting that

#

is that reasonable enough - it seems to work

lucid crystal
#

yeah

summer hamlet
#

sweet, cool -thanks again!

onyx monolith
#

depending on your API, your response may not match your type. If you want strict validation with type inference check out zod

lucid crystal
#

if it's currently typed as object you probably don't need the Omit

#

"probably" only because... if it's not optional on the base type (but it is definitely optional here) idk what's supposed to happen

lucid crystal
#

but if it's coming from user input then yeah you'd definitely want validation

onyx monolith
#

yeah if its internal its probably not necessary

summer hamlet
#

Thanks, i've seen many mentions of zod, i'm happy to bring it in - but that seems to require the types to be defined in zod, and you use zod to generate the type defs

lucid crystal
#

yeah

summer hamlet
#

in this case it's internal, so if i can dodge some complexity, but totally take your point!

lucid crystal
#

!close