首页 > 解决方案 > 如何明确告诉 TS 函数的返回值应该是某种类型?

问题描述

如果我有类似的东西,

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())
}

我收到打字稿错误,

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

如何确保 TS,value传递给的道具ChildComponent是 type string

标签: javascriptreactjstypescript

解决方案


这可以通过类型断言来解决

一个典型的用例是尖括号语法:

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

但是,<string>在 tsx 文件中会发生冲突,因为它可能会与 html 标签混淆。

在这种情况下,您可以对 jsx 和 tsx 文件使用 as-style 断言,typescript 已经为您准备好了:

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

推荐阅读