为什么以下打字稿类型联合代码无效?

Why is the following typescript type union code invalid?

我正在尝试创建一个接受字符串或接受 returns 字符串的函数,但出现以下错误:

代码

interface Props {
    title: (values: string) => string | string;
}

const a: Props = {
    title: 'Title'
}

const b: Props = {
    title: (t) => t
}

错误:

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

Playground Link

你只需要将 (values: string) => string 括在括号中,否则 union 将应用于 return 类型并读取 string | string:

interface Props {
    title: ((values: string) => string) | string;
}

更简洁的选项是将 (values: string) => string 提取到它自己的类型:

type TitleBuilder = (values: string) => string;

interface Props {
    title: TitleBuilder | string;
}