[英]Why is the following typescript type union code invalid?
I am trying to create a function that either accepts a string or accepts a function that returns a string but I get the following error: 我正在尝试创建一个接受字符串或接受返回字符串的函数的函数,但出现以下错误:
Code 码
interface Props {
title: (values: string) => string | string;
}
const a: Props = {
title: 'Title'
}
const b: Props = {
title: (t) => t
}
Error: 错误:
Type '{ title: string; }' is not assignable to type 'Props'.
Types of property 'title' are incompatible.
Type 'string' is not assignable to type '(values: string) => string'.
const a: Props
You just need to wrap (values: string) => string
in parentheses, otherwise union is applied to return type and reads string | string
您只需要将
(values: string) => string
包装在括号中,否则将使用union来返回类型并读取string | string
string | string
: string | string
:
interface Props {
title: ((values: string) => string) | string;
}
Slightly cleaner option would be extracting (values: string) => string
to its own type: 稍微干净一点的选项将提取
(values: string) => string
为自己的类型:
type TitleBuilder = (values: string) => string;
interface Props {
title: TitleBuilder | string;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.