Home > Software design >  Specifying the types of parameters in a function that takes 2 parameters
Specifying the types of parameters in a function that takes 2 parameters

Time:11-26

I have a function that takes two parameters as below. If they are in an object, I can specify their types as follows

    const renderItem = ({ item, index }: { item: string, index: number }) => {

        return (
            null
            )
    }

If parameters are not in an object like below, how can I specify their type?

const renderItem = (item, index) => {

    return (
        null
    )
}

CodePudding user response:

You can use a tuple type. This makes typing multiple parameters with a single type possible.

const renderItem = (...[item, index]: [string, number]) => {}

Or give each parameter its own explicit type.

const renderItem = (item: string, index: number) => {}

Playground

  • Related