2017-07-27 73 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,我認爲你是正確的,重載函數將是一個更好的方法在這裏 –