Mike K
Mike K

Reputation: 6481

How to tell TS explicitly that the return value of a function will be expected to be of a certain type?

If I have something like,

const ChildComponent = ({value}: {value: string}) => {
    return <div>{value}</div
}

const ParentComponent = () => {
    return (
        <ChildComponent value={getValue(true)} />
    )
}

const getValue = (getCurrent?: boolean): Array<string> | string => {
    const currentYear = new Date().getFullYear()

    if (getCurrent) return currentYear.toString()

    return Array.from({length: 5}, (_, index) => (currentYear + index).toString())
}

I get a Typescript error,

<ChildComponent value={getValue(true)} />
                ^^^^^
Type 'string[] | string' is not assignable to type 'string | undefined'
  Type 'string[]' is not assignable to type 'string'

How do I ensure TS, that the prop value passed to ChildComponent will be of type string?

Upvotes: 0

Views: 62

Answers (2)

glinda93
glinda93

Reputation: 8459

This can be solved by type assertion

A typical use case is angle-bracket syntax:

const value: string = <string> getValue(true)

However, <string> will conflict in tsx files because it can be confused with html tags.

In this case, you can use as-style assertion for jsx and tsx files, typescript has prepared for you:

<ChildComponent value={getValue(true) as string} />

Upvotes: 3

Pramod Mali
Pramod Mali

Reputation: 1798

It seems a problem with your ChildComponent. It's expecting only string but possible values could be a string or string array.

You could update your child component as follow:

const ChildComponent = ({value}: {value: string | Array<string>}) => {
    return <div>{value}</div
}

Upvotes: 0

Related Questions