#Check if optional property exists in const object?

5 messages · Page 1 of 1 (latest)

cunning kraken
#

Hey all,

suppose an object like

const foo = {
  someProp: {
    test: false
  }
} satisfies Record<string, {bar?: string, test: boolean}>

Is it possible to check whether entries in foo have property type and if so, access the type?

E.g suppose we want to access type in a function like

declare function fn<
  K extends keyof typeof foo,
  // T won't work because 'type' does not exist on foo :(
  T extends typeof foo[K]['type']
>(): void

The extend of T unfortunately won't work, because type does not exist on foo[K], but is there a way to check if type exist and then being able to access the type and if not, return a default value?

quasi meteorBOT
#
Peter Hase#2613

Preview:```ts
const foo = {
someProp: {
test: false
}
} satisfies Record<string, {bar?: string, test: boolean}>

declare function fn<
K extends keyof typeof foo,
// T won't work because 'type' does not exist on foo :(
T extends typeof foo[K]['type']

(): void```

frank prairie
#

without the implementation/call sites/return type it's hard to know what's fair game, but you could add another type parameter:

quasi meteorBOT
#
mkantor#7432

Preview:```ts
...
declare function fn<
F extends Record<string, {type?: string}>,
K extends keyof F,
T extends F[K]['type']

(): void```

cunning kraken
#

Sorry for the belated answer @frank prairie , appreciate your help, thanks!