打字稿泛型奇怪的行为

时间:2017-07-27 13:43:56

标签: typescript

export function resize<T extends File | Blob>(input: T, w: number, h: number): Promise<T> {
  return Promise.resolve(new File([new Blob()], 'test.jpg'))
}

错误:

  

(48,3)TS2322:类型'Promise'不能分配给'Promise'类型。     类型“文件”不能指定为“T”类型。

无法理解为什么?

2 个答案:

答案 0 :(得分:0)

重点是您的通用参数T是一个FileBlob继承的类。你要归的只是一个简单的Promise<File>。这显然不能分配给继承的类型。我不确定input参数究竟是什么以及它如何影响输出,但返回类型肯定应该是Promise<File>

export function resize<T extends File | Blob>(input: T, w: number, h: number): Promise<File> {
  return Promise.resolve(new File([new Blob()], 'test.jpg'))
}

答案 1 :(得分:0)

这对我有用,但这看起来很奇怪

if (isFile(input)) {
    const f = new File([blob], input.name)
    resolve(f as T)
} else if (isBlob(input)) {
    resolve(blob as T)
}

从:

export
function resize<T extends Blob | File>(input: T, width: number, height: number): Promise<T> {

    return new Promise((resolve, reject) => {

      const image = new Image()

        image.onload = () => {

            const canvas = document.createElement('canvas')
            canvas.width = width
            canvas.height = height

            pica.resize(image, canvas)
                .then((result) => pica.toBlob(result, input.type, 85))
                .then((blob: Blob) => {

                    if (isFile(input)) {
                      const f = new File([blob], input.name)
                      resolve(f as T)

                    } else if (isBlob(input)) {
                      resolve(blob as T)

                    }
                })
                .catch(err => reject(err))
        }

        image.src = URL.createObjectURL(input)

    })
}
相关问题