Home > Enterprise >  What does this syntax mean in React Native and TypeScript?
What does this syntax mean in React Native and TypeScript?

Time:10-27

var = ({ data }: { data: interfaceModel }) => (
  // data is used here
)

What does this syntax mean? I know that the second data has an interface of interfaceModel. But why are there two occurrences of data?

CodePudding user response:

It means that it is a function and its argument must be an object which should contain a key data and data should contain keys which are defined in interfaceModal, { data } this is the argument, { data: interfaceModel } this is the type

example

interface interfaceModel {
   name:string
   age:number
}
interface DataModel {
   data: interfaceModel
}

const myFunc = ({ data }: { data: interfaceModel }) => (
  // data is used here
)

let myData:DataModel = {data:{name:'Your name', age:32}}

myFunc(myData);

myFunc can also be defined like

   const myFunc = (myData:dataModel) => (
      // myData.data is used here
    ) 

CodePudding user response:

var = ({ data }: { data: interfaceModel }) => (
  // data is used here
)

First { data } is a destructured property. You can write the same function in this way:

var = (props: { data: interfaceModel }) => (
  props.data // valid
)

Second {data: interfaceModel} is just a literal representation of type.

You can rewrite it in this way:

interface Data {
 data: interfaceModel
}

var = (props: Data) => (
  props.data // valid
)
  • Related