javascript - 如何明确告诉 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
?
解决方案
这可以通过类型断言来解决
一个典型的用例是尖括号语法:
const value: string = <string> getValue(true)
但是,<string>
在 tsx 文件中会发生冲突,因为它可能会与 html 标签混淆。
在这种情况下,您可以对 jsx 和 tsx 文件使用 as-style 断言,typescript 已经为您准备好了:
<ChildComponent value={getValue(true) as string} />
推荐阅读
- ibm-cloud - 无法在 IBM Cloud 中创建项目
- date - 在 Camunda 中显示结果
- matlab - MATLAB中的指数曲线拟合不佳
- tensorflow - MirroredVariable 在副本上有不同的值(零,除了在一个设备上)
- node.js - 未使用 Adobe 的适用于 nodejs 的 PDF SDK 设置权限
- arrays - Char** 结构成员无效写入
- lisp - 如何获取在 Common Lisp 中定义函数的文件名?
- c++ - 在 SDL 中查找屏幕上的平均颜色
- python - 确定我可以对子序列求和多少次以获得Python中给定k数的方法
- python - 如何将 python 代码复制到 R 以查找重复项?