2017-07-27 68 views
1
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:Type 'Promise' is not assignable to type 'Promise'. Type 'File' is not assignable to type 'T'.

不明白为什么?

+0

从来没有过过,但不应该是'Promise .resolve'? – Will

+0

谢谢,它的工作原理是这样的 返回Promise.resolve(new File([new Blob()],'test.jpg'))Promise 但我仍然不明白 –

+0

Gah,我只是不知道足够的打字稿的泛型(和文档,在一个快速squizz,没有足够的信息 - 他们甚至没有涵盖'扩展文件| Blob'语法,这是我的头从头开始)。我有点震惊,因为Promise '*作品*。怎么回事,[Anders?](https://en.wikipedia.org/wiki/Anders_Hejlsberg)我想你会*使用'Promise .resolve',并且'Promise '会导致在一个空值被返回...你确定吗? – Will

回答

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')) 
} 
+0

关键是我需要返回file或根据输入类型 这为我工作一滴,但是这看起来很奇怪 '\t \t \t如果(ISFILE(输入)){ \t \t \t常量F =新文件([BLOB],input.name) 决心(F为T) }否则如果(isBlob(输入)){ 决心(BLOB如T) }' –

0

这为我工作,但是这看起来很奇怪

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

from:

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) 

    }) 
} 
+0

您仍然无法安全地返回'Promise '。如果'T'是'File'的子类呢?你不能返回相同的类型。你可能想要的只是一个重载的函数声明,一个接受'File'并返回'File',另一个接受'Blob'并返回一个'Blob'。仿制药并没有帮助你。 – jcalz

+0

谢谢jcalz,我认为你是正确的,重载函数将是一个更好的方法在这里 –