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

时间:2018-05-19 11:57:32

标签: javascript typescript typescript2.0

我正在尝试创建一个接受字符串或接受返回字符串的函数的函数,但是我收到以下错误:

代码

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

1 个答案:

答案 0 :(得分:3)

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

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

稍微清洁的选项是将(values: string) => string提取为自己的类型:

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

interface Props {
    title: TitleBuilder | string;
}