Kevin Kumar
Kevin Kumar

Reputation: 71

Give React Prop an interface

Hello guys I have some problem, so I like to work with interfaces to not mix up stuff and also to keep readability and have intellisense Now my Problem, i would like to use this also with given data (through props), but I cant work out how to do so here is an example I wrote https://codesandbox.io/s/practical-easley-y82ox?file=/src/App.js:0-748

So I would like to get an error before its rendered that the given prop is not the correct type How would this possible ? I tried writing the type inside the constructor function Test({ q }: Question) and also the given PropType by React -> dont get intellisense and also couldnt figure it out with the interface I am sure i am missing something or not understanding the real difference, I am not trying to work it out for hours. Would be glad for some help

Upvotes: 0

Views: 49

Answers (2)

aleksxor
aleksxor

Reputation: 8340

There are some issues with your code:

  • as noted in John's answer you have to rename your files' extensions to .tsx for TS to work correctly on them
  • right now your Question interface is defined as
interface Question {
    question: String;
    answers: [];
}

While the testCorrect variable's type should be defined as:

interface Question {
    question: string
    answers: string[]
}
  • the type of Test component then should be written as:
interface TestProps {
  q: Question
}

function Test({ q }: TestProps): JSX.Element {
...
}

Or if you prefer to make it inline:

function Test({ q }: { q: Question }): JSX.Element {
...
}

TS playground

Upvotes: 1

John
John

Reputation: 451

From your code sandbox, your file is in JavaScript .js not TypeScript .ts or preferably for React .tsx which will give you intellisense.

Upvotes: 1

Related Questions