Home > Mobile >  Why can't I specify the widget as the key (using keyof) to constrain the type?
Why can't I specify the widget as the key (using keyof) to constrain the type?

Time:08-09

What I expect is:

The C component should be mistake, because I set the widget equals "Input", which only has constrained key that is "a" of type F, when I set the "b" property's value, it should be mistake, but it isn't.

type F = {
  Input: {a: string},
  Select: {b: string},
}

export function createView<
  ComponentName extends keyof F,
>() {
  function InternalView (
    props:  {
      widget: ComponentName
    } & F[ComponentName]
  ) {
    return <div>1</div>
  }
  return InternalView
}

const View = createView()
const C = () => <View widget="Input" a="1" b="1"/>  // should be mistake, property b is not allowed

CodePudding user response:

I don't think that is how TS Generics work. You need to pass an argument so that the props type will evaluate to your expected type. Consider the following updates to your code:

type F = {
  Input: {a: string},
  Select: {b: string},
}

export function createView<
  ComponentName extends keyof F,
>() {
  function InternalView (props: F[ComponentName]) {
    return <div>1</div>
  }
  return InternalView
}

const InputView = createView<"Input">();
const C = () => <InputView a="1" b="2" />; // will cause TS error because of prop b
  • Related