gpt4 book ai didi

javascript - 为什么以下 typescript 类型联合代码无效?

转载 作者:行者123 更新时间:2023-11-28 17:31:01 24 4
gpt4 key购买 nike

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

代码

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 将应用于返回类型并读取 string |字符串:

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

稍微干净一点的选项是将 (values: string) => string 提取为其自己的类型:

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

interface Props {
title: TitleBuilder | string;
}

关于javascript - 为什么以下 typescript 类型联合代码无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50425039/

24 4 0
文章推荐: css -

垂直对齐到

Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com