Home > Blockchain >  Type restriction in props is not recognized in the function
Type restriction in props is not recognized in the function

Time:12-14

Why is the following object extraction flagged as incorrect by the compiler? playground link

type SplitTextProps<T, N extends keyof T> = T[N] extends string
  ? {
      object: T
      getter: N
    }
  : never

const splitText = <T, N extends keyof T>({
  object,
  getter
}: SplitTextProps<T, N>) => {
  const value = object[getter]
  return value.split(' ')
}

interface Datatype {
  value: string
  id: number
}

const record: Datatype = { value: 'Green is good', id: 5 }
const result = splitText({ object: record, getter: 'value' })

console.log(result)

value.split(' ') is marked as incorrect despite the type definition on SplitTextProps. The exact error message is

Property 'split' does not exist on type 'T[N]'


Edit (Adding more info): In fact, the restriction actually works when trying to pass incorrect props, the compiler throws the following error when trying to use splitText({object: record, getter : 'id'})

Argument of type '{ object: Datatype; getter: string }' is not assignable to parameter type 'never'.

☝️ because id prop of interface Datatype isn't a string. Only the happy path fails within splitText func

  • Related