#How to ensure nested object's properties match their types with siblings.

1 messages · Page 1 of 1 (latest)

patent sableBOT
#
rygar900#0

Preview:ts const obj = { light: { one: "value", // Should throw a type error here since `light` is missing `two` key }, dark: { one: "value", two: "value", }, }

crimson garden
#

use a cif

#

!:cif

patent sableBOT
#
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 }
crimson garden
#

that way you can infer the child type

winter seal
#

Ok, I'll look into that. Thanks!