Typescript嵌入的泛型类型未正确遵循泛型参数

问题描述 投票:0回答:1

我创建了一个通用的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'.
typescript typescript-generics
1个回答
0
投票
您收到这些错误是因为本质上您的Custom<ImageType>解析为-

{ type: ImageType; source?: string | number | undefined; mime: string | undefined; other?: string; stuff?: string; }

现在您正在尝试将该类型分配给解析为Image<ImageType>Require|URI,并且您的Custom<ImageType>无法分配给Require|URI
热门问题
推荐问题
最新问题