#Why typescript doesn't show error

9 messages · Page 1 of 1 (latest)

glossy compass
#

in typescript I want to create type from array of objects

if array object is

const columns = [{key: "a"}, {key: "b"}]
// row should be
const row = {a: "", b: ""}

I do like this but why must_be_error does not show error in typescript?

export type ColumnsKeys = {
  key: string,
  label: string | ReactNode
}[]

type RowType<T extends ColumnsKeys> = { [K in T[number]['key']]: string | ReactNode };

const a: ColumnsKeys = [{
  key: "name",
  label: "hey"
}]

const columns: RowType<typeof a>[] = [{
  name: "",
  must_be_error: ""
}]
rugged cloud
#

typescript allows extra properties

#

actually wait no it's a literal here

#

i think it's just resolving to string

#

sec

#

yeah a is losing its type info

#

i missed that entirely

#

!:cif

smoky trellisBOT
#
Gerrit0#7591
`!gerrit0:cif`:

If you want to both validate that a variable matches a specific type and also let TypeScript narrow the variable if possible, a constrained identity function is usually the best way to do this:

interface Foo {
  foo: string | number;
}
function createFoo<T extends Foo>(x: T) { return x }

const foo = createFoo({ foo: 123 })
//    ^? const foo: { foo: number }