【发布时间】:2020-04-24 11:55:00
【问题描述】:
我有一个函数可以验证 JSON 响应以确保它对应于给定的形状。
这是我定义所有可能的 JSON 值的类型——取自 https://github.com/microsoft/TypeScript/issues/1897#issuecomment-338650717
type AnyJson = boolean | number | string | null | JsonArray | JsonMap;
type JsonMap = { [key: string]: AnyJson };
type JsonArray = AnyJson[];
现在我有一个函数可以在给定要验证的对象和形状为T 的模拟对象的情况下进行验证。
function isValid<T extends AnyJson>(obj: AnyJson, shape: T): obj is T {
// ... implementation
}
但是,当我尝试使用接口和真实对象调用函数时,我在类型参数中的 Thing 下遇到类型错误
interface Response {
Data: Thing[]; // Thing is an interface defined elsewhere
};
isValid<Response>(data, { Data: [] })
// ^^^^^^^^
Type 'Response' does not satisfy the constraint 'AnyJson'.
Type 'Response' is not assignable to type 'JsonMap'.
Index signature is missing in type 'Response'.
奇怪的是,当Response 是类型而不是接口时,这种情况不会发生,例如
type Response = {
Data: Thing[];
};
但我确实遇到了同样的错误,但在Thing 本身上,它仍然是一个接口:
Type 'Response' does not satisfy the constraint 'AnyJson'.
Type 'Response' is not assignable to type 'JsonMap'.
Property 'Data' is incompatible with index signature.
Type 'Thing[]' is not assignable to type 'AnyJson'.
Type 'Thing[]' is not assignable to type 'JsonArray'.
Type 'Thing' is not assignable to type 'AnyJson'.
Type 'Thing' is not assignable to type 'JsonMap'.
Index signature is missing in type 'Thing'.
所以我的问题是,为什么这种预期的缩小不会发生在接口上,而只是发生在类型上?
【问题讨论】:
标签: typescript