简体   繁体   中英

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 ?

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} />

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM