Typescript 类型中缺少索引签名:为什么这是一个错误?
采用以下类型脚本:Typescript 类型中缺少索引签名:为什么这是一个错误?,typescript,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
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);
}
沃特?此外,如果我们更改LinkOrMessage
类型,使其不是一个联合,例如,将其简化为{link:string}
,错误就会消失!如果我们简化为{message:string}
也一样。很明显,联合体中的每种类型都可以分配给POJO
,而联合体本身却不是
有人能解释一下这种行为吗?自从TypeScript 2.0以来,有一种东西叫做a,它允许您将没有索引签名的类型的某些对象分配给具有索引签名的类型的变量。但是关于何时推断隐式索引签名的规则有一点(因为有些人质疑它们)。特别是,它们之间的相互作用似乎在进行 我认为对您来说,好消息可能是您看到的特定问题可能是在TypeScript v2.4中引入的,并在TypeScript v2.6.1中修复。不太好的消息是v2.6.1还没有发布;您可以尝试编译以查看它是否已清除
祝你好运 自从TypeScript 2.0以来,有一种东西叫做a,它允许您将没有索引签名的类型的某些对象分配给具有索引签名的类型的变量。但是关于何时推断隐式索引签名的规则有一点(因为有些人质疑它们)。特别是,它们之间的相互作用似乎在进行 我认为对您来说,好消息可能是您看到的特定问题可能是在TypeScript v2.4中引入的,并在TypeScript v2.6.1中修复。不太好的消息是v2.6.1还没有发布;您可以尝试编译以查看它是否已清除 祝你好运
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; }'