gpt4 book ai didi

typescript - 类型 : why is this an error? 中缺少索引签名

转载 作者:行者123 更新时间:2023-12-05 02:17:50 24 4
gpt4 key购买 nike

采用以下 typescript :

type Primitive = undefined | null | boolean | number | string;

// A POJO is just supposed to be your typical object, with nothing
// fancy, but where we don't exactly know what's in it.
interface POJO {
[key: string]: Primitive | POJO;
}

好的,所以 POJO 只是应该表示一些通用对象,但是是一个非常简单的对象。可能是我要 JSON.stringify 或其他内容。现在这是有问题的代码:

// Some functions implemented elsewhere...
declare function post(path: string, data: POJO): Promise<Response>;
declare function getToken(): string;

type LinkOrMessage = {link: string} | {message: string};

function specialPost(path: string, data: LinkOrMessage): Promise<Response> {
const body = {
...data,
token: getToken(),
};

// Error: see below...
return post(path, body);
}

错误是:

Argument of type '{ token: string; link: string; } | { token: string; message: string; }'
is not assignable to parameter of type 'POJO'.

Type '{ token: string; link: string; }'
is not assignable to type 'POJO'.

Index signature is missing in type '{ token: string; link: string; }'

哇?此外,如果我们更改 LinkOrMessage 类型,使其不是联合,例如将其简化为 {link: string},错误消失了!如果我们简化为 {message: string} 也是一样。很明显联合中的每个类型都可以分配给 POJO,但联合本身不是?

有人可以阐明这种行为吗?

最佳答案

从 TypeScript 2.0 开始,就有了 implicit index signature 这样的东西。它允许您将某些没有索引签名的类型的对象分配给具有索引签名的类型的变量。但是何时推断隐式索引签名的规则有点questionable (因为有些人质疑他们)。特别是,implicit index signatures and the spread operator 之间的交互似乎正在发生某些事情。 .

我认为对您来说好消息可能是您看到的特定问题可能是 bug在 TypeScript v2.4 中引入并在 TypeScript v2.6.1 中修复。不太好的消息是 v2.6.1 尚未发布;您可以尝试针对 typescript@next 进行编译看看它是否被清除了。

祝你好运!

关于typescript - 类型 : why is this an error? 中缺少索引签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46899601/

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