2016-12-12 161 views
4

我在打字稿用window.fetch取,但我不能直接投的迴應我的自定義類型:如何使用打字稿

我被鑄造無極導致黑客攻擊我身邊這樣的中間「任意」變量。

這樣做的正確方法是什麼?

import { Actor } from './models/actor'; 

fetch(`http://swapi.co/api/people/1/`) 
     .then(res => res.json()) 
     .then(res => { 
      // this is not allowed 
      // let a:Actor = <Actor>res; 

      // I use an intermediate variable a to get around this... 
      let a:any = res; 
      let b:Actor = <Actor>a; 
     }) 
+0

嗯,'json'包含普通對象,那麼如何將它轉換爲實例呢?你需要使用類似於'Actor.from'的東西來創建一個帶有數據的'New Actor'。 – Bergi

+0

爲什麼「不允許」?你嘗試時會得到什麼錯誤? – Bergi

+0

以及您使用的是哪些定義,因爲[抓取不在打字稿庫中](https://github.com/Microsoft/TypeScript/pull/12493) –

回答

0

如果您在@types/node-fetch看一看,你會看到身體定義

export class Body { 
    bodyUsed: boolean; 
    body: NodeJS.ReadableStream; 
    json(): Promise<any>; 
    json<T>(): Promise<T>; 
    text(): Promise<string>; 
    buffer(): Promise<Buffer>; 
} 

這意味着,你可以使用仿製藥,以達到你想要的。我沒有測試這個代碼,但它看起來像這樣:

import { Actor } from './models/actor'; 

fetch(`http://swapi.co/api/people/1/`) 
     .then(res => res.json<Actor>()) 
     .then(res => { 
      let b:Actor = res; 
     }); 
+1

將泛型類型添加到'預期的0類型參數中,但得到1',但也許這是因爲我沒有使用'node-fetch'。原生提取的類型可能不同? – Kokodoko