[英]I am confused about this simple component in React with TypeScript
我是 TypeScript 的新手,在這個簡單的示例中,我創建了一個組件來從假 API 中獲取數據並在map
迭代中顯示它們:
import React, { FC, useState } from 'react'; const GetData = (): Promise<[]> => { return fetch('https://randomuser.me/api/?results=5').then((response: any) => response.json()).then((data: any) => data.results); } const App: FC<{}> = () => { const [users, setUsers] = useState<[]>([]); const getUsers = (): void => { GetData().then((data: []) => setUsers(data)); } return ( <div> { <ul> { users.map((item: any, index: number) => ( <li key={`user-${index}`}>{`${item.name.first} {item.name.last}`}</li> )) } </ul> } <button onClick={getUsers}>Load</button> </div> ) } export default App;
這段代碼運行良好。 但我不確定我的代碼是否正確......在這個例子中,我有:any
類型的函數輸入(例如在 promise 鏈中)那么,這個例子是否正確? 當我在 output 中有一個嵌套數組時,我能否在 arguments 中使用許多任何類型?
第二個,我沒有為GetData
添加類型:
但這是一個const
,我應該像這樣聲明它們:
const age: number = 40;
但我沒有收到任何錯誤?
謝謝
當您使用any
時,您會錯過大多數 typescript 的錯誤發現能力。 您基本上是在說,“相信我,這很好”,因為any
可以分配給任何類型。
有幾個地方我們可以改進您的類型,也有一些不准確的類型。 Promise<[]>
實際上意味着這是一個空數組[]
的 promise 。 您希望它返回一組用戶: Promise<User[]>
。
您可能已經在您的應用程序的其他地方輸入了此User
object。 在這里,我只是定義了該組件所需的屬性。
interface User {
name: {
first: string;
last: string;
}
}
調用fetch
返回Promise<Response>
其中Response
是支持 .json .json()
方法的內置 object 類型。 因此,與其(response: any)
不如只做(response)
並使用推斷的類型。 該.json()
方法返回Promise<any>
,因此推斷的data
類型是any
。 此時您可以選擇斷言data
是 object ,其屬性results
包含User
對象數組,但您也可以堅持使用推斷的any
並依賴函數的返回類型來斷言。
const GetData = (): Promise<User[]> => {
return fetch('https://randomuser.me/api/?results=5')
.then((response) => response.json())
.then((data) => data.results);
}
現在到組件。 我們的 state 是一個User
數組,而不是一個空數組。
const [users, setUsers] = useState<User[]>([]);
更改后,您可以從(data: [])
和(item: any, index: number)
中刪除類型。 當您在鏈中具有適當的類型時,通常不需要在回調中斷言類型。 當您調用users.map
時,該item
已知具有User
類型,因為users
被鍵入為User[]
。
當您使用Promise
泛型定義一個時,您不應將回調函數的類型添加到鏈中。 例如像這樣寫你的鏈:
const GetData = (): Promise<User[]> => {
return fetch('https://randomuser.me/api/?results=5')
.then((response) => response.json())
.then((data) => data.results);
}
關於const age: number = 40;
when you define a const
and assign function to that, means you are create a function and TypeScript considers it will be a function and not a primitive value, therefore, you shouldn't add type for const
after that name. 但是當你設置這樣的東西時: const age: number = 40;
上面的代碼意味着,您正在定義一個原始值,並且應該在名稱之后設置類型。
使用any
是一種蠻力方法,它首先放棄了使用 TypeScript 的所有好處。 它有效,但不推薦。
給定const age = 40
, TypeScript 知道您正在分配一個數字。 右側的表達式只能是數字。 它可以從中推斷出類型,因此您無需明確說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.