为何以下TypeScript类型联合代码出现类型不兼容错误?
解决TypeScript Props接口中title属性联合类型的错误
嘿,这问题我熟!你之所以会遇到这个类型不兼容的错误,核心是联合类型的位置写错了。
先看你原来的代码:
interface Props { title: (values: string) => string | string; } const a: Props = { title: 'Title' } const b: Props = { title: (t) => t }
你写的(values: string) => string | string,其实是在定义一个返回值为string类型的函数(因为string | string本质还是string),所以TypeScript会认为title只能是这个函数类型,自然字符串'Title'就无法赋值给它,触发了类型不兼容的错误。
正确的写法
你需要把联合类型放在整个函数类型和string之间,这样才能表示title既可以是字符串,也可以是指定的函数:
interface Props { title: ((values: string) => string) | string; } // 现在这两个赋值都不会报错啦 const a: Props = { title: 'Title' } const b: Props = { title: (t) => t }
优化写法(可选)
如果觉得这个类型定义有点绕,可以用类型别名拆分一下,让代码更清晰:
// 先定义title的可选类型 type TitleValue = string | ((value: string) => string); interface Props { title: TitleValue; }
这样不管是直接传字符串,还是传符合要求的函数,TypeScript都能正确识别啦~
内容的提问来源于stack exchange,提问作者Ciaran Liedeman
相关产品推荐
相关产品推荐

