Javascript 为什么以下类型脚本类型联合代码无效?

Javascript 为什么以下类型脚本类型联合代码无效?,javascript,typescript,typescript2.0,Javascript,Typescript,Typescript2.0,我试图创建一个接受字符串或接受返回字符串的函数,但出现以下错误: 代码 错误: 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 您只需将(值:str

我试图创建一个接受字符串或接受返回字符串的函数,但出现以下错误:

代码

错误:

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

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

interface Props {
    title: ((values: string) => string) | string;
}
稍微干净一点的选项是将
(值:string)=>string
提取为它自己的类型:

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

interface Props {
    title: TitleBuilder | string;
}

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

interface Props {
    title: ((values: string) => string) | string;
}
稍微干净一点的选项是将
(值:string)=>string
提取为它自己的类型:

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

interface Props {
    title: TitleBuilder | string;
}

这是我自己发现的,谢谢!这是我自己发现的,谢谢!