#Infer return of a function based on partial object inside

14 messages · Page 1 of 1 (latest)

light bluffBOT
#
.alfon#0

Preview:```ts
type propType = "checkbox" | "number" | "list"

function getPropertyValue<Type extends propType>(
prop: Type
) {
if (prop === "checkbox")
return true as Type extends "checkbox"
? boolean
: null
if (prop === "number")
return 5 as Type extends "number" ? number : null
...```

last jay
#

Using map to selectively determine the return types of a generic function is great and all but the cons is that I have to list all of the unions as the keys of map. Is there a way to provide a partial object for this and have a fallback?

nova dock
#

could do this

light bluffBOT
#
that_guy977#0

Preview:ts ... const map: Partial<Record<propType2, unknown>> = { checkbox: true, number: 5, } ...

last jay
# light bluff

That solves the error, but it just infer anything inside the map as unknown :/

nova dock
#

hm, seems like satisfies isn't enough here

#

!:cif

light bluffBOT
#
gerrit0#0
`!gerrit0:cif`:

If you want to both validate that a variable matches a specific type and also let TypeScript narrow the variable if possible, you may be able to use satisfies. If satisfies isn't flexibile enough, a constrained identity function is the best way to do this:

interface Foo {
  prop: string | number;
}

const foo = { prop: 123 } satisfies Foo
//    ^? const foo: { prop: number }
// errors if foo is not assignable to Foo

function createFoo<T extends Foo>(x: T) { return x }

const foo2 = createFoo({ prop: 123 })
//    ^? const foo2: { prop: number }
last jay
#

hmm

#

this is pain ||peko||, i suppose i dont mind listing all the union into map

last jay
#

wait what does that mean in this context

pseudo raft
#

Why not:

const map = {
    checkbox: true,
    number: 5,
    list: null,
}
return map[prop]
last jay