【发布时间】:2020-07-25 11:25:49
【问题描述】:
我创建了一个通用的 Image 接口,然后当我需要在另一个通用接口中使用相同的通用参数时,Typescript 似乎无法正确推断类型。似乎 Typescript 尝试使用“|”来获取每个选项运算符。
我是不是做错了什么?
type ImageType = "require" | "uri";
interface Common<T extends ImageType> {
type: T;
other?: string;
stuff?: string;
}
interface Require extends Common<"require"> {
source: number;
mime: string;
}
interface URI extends Common<"uri"> {
source: string;
mime?: string;
}
type Image<T extends ImageType> =
T extends "require" ? Require
: T extends "uri" ? URI
: Common<T>;
interface Custom<T extends ImageType> {
type: Image<T>["type"];
source?: Image<T>["source"];
mime: Image<T>["mime"];
other?: string;
stuff?: string;
}
const example0 = (image: Image<ImageType>) => "do something";
const exemple1 = (custom: Custom<ImageType>) => custom.source &&
example0({type: custom.type, source: custom.source, mime: custom.mime})
最后一行产生的内容:
(我自愿选择Custom<ImageType> 和Image<ImageType> 的类型,因为我想要这些示例中的任何类型的图像)
Argument of type '{ type: ImageType; source: string | number; mime: string | undefined; }' is not assignable to parameter of type 'Require | URI'.
Type '{ type: ImageType; source: string | number; mime: string | undefined; }' is not assignable to type 'URI'.
Types of property 'source' are incompatible.
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
【问题讨论】:
-
Common<T extends ImageType>这没有任何意义。如何从字符串文字类型扩展?我认为它应该只是公共接口定义中的type: ImageType。 -
您可以在泛型类型中扩展字符串文字以限制可能的字符串。请尝试以下操作:
ts type options = "a" | "b" | "c"; interface Example<T extends options> { type: T; } const test: Example<"d"> = {type: "d"}我的意思是将公共接口泛型参数限制为"require" | "uri"。现在我可以删除通用接口的泛型并保留自定义接口,但这不能解决我的问题。 -
是的,我明白你现在的意思了,你使用的是仅限于字符串子集的泛型。 typescript
extends关键字在这种情况下有点误导。
标签: typescript typescript-generics