[英]"Any" data type for GraphQL Query Return Type
我對 Typescript 有點陌生,並且在數據類型方面遇到了一些問題。 有人告訴我,我應該避免使用“任何”數據類型,因為它否定了使用 Typescript 的全部意義。 但是,我無法更改數據類型。 例如,
當我運行 GraphQL 查詢時,我使用這個:
login({
variables: {
email: email,
password: password,
},
})
.then(({ data }: any) => {
localStorage.setItem('token', data.loginEmail.accessToken);
setShouldRedirect(true);
//props.history.push("/panel");
})
data.loginEmail.accessToken
是一個字符串,所以我將:any
更改為字符串,但出現以下錯誤:
Argument of type '({ data }: string) => void' is not assignable to parameter of type '(value: ExecutionResult<any>) => void | PromiseLike<void>'.
Types of parameters '__0' and 'value' are incompatible.
Type 'ExecutionResult<any>' is not assignable to type 'string'. TS2345
如果我將類型更改為object
,我會Property 'data' does not exist on type '{}'. TS2339
得到Property 'data' does not exist on type '{}'. TS2339
Property 'data' does not exist on type '{}'. TS2339
但文檔還說突變返回一個對象。 因此,如果不是對象或字符串,我還能如何為此類對象指定數據類型? 甚至有可能嗎?
同樣,當我在查詢后映射這樣的項目時:
{data &&
data.users.nodes &&
data.users.nodes.map((c: any, i: any) => (
<li key={i}>
Id: {c.id}, First Name: {c.firstName}, Last Name: {c.lastName},
Email: {c.email}, phoneNumber: {c.phoneNumber}
</li>
))}
我還能如何指定 c 和 I? i 沒有簡單的整數選項。
編輯:
架構:
loginEmail(
email: String!
password: String!
): SignInResponse!
type SignInResponse {
accessToken: String!
}
GraphQL 代碼:
export type MutationLoginEmailArgs = {
email: Scalars['String'],
password: Scalars['String']
};
如果您使用的是 TypeScript,您應該為鈎子返回的數據和傳遞給它的變量生成類型。 類型生成可以使用Apollo CLI或GraphQL 代碼生成器來完成。
獲得類型后,您可以將它們與鈎子一起使用,如文檔中所示。 通過這樣做,您將避免在使用鈎子返回的data
屬性時必須顯式分配類型。 您還將為傳遞給鈎子的任何變量添加類型安全性。
文檔中的示例用法:
interface RocketInventory {
id: number;
model: string;
year: number;
stock: number;
}
interface RocketInventoryData {
rocketInventory: RocketInventory[];
}
interface RocketInventoryVars {
year: number;
}
const GET_ROCKET_INVENTORY = gql`
query getRocketInventory($year: Int!) {
rocketInventory(year: $year) {
id
model
year
stock
}
}
`;
export const SomeComponent = () => {
const { loading, data } = useQuery<RocketInventoryData, RocketInventoryVars>(
GET_ROCKET_INVENTORY,
{ variables: { year: 2019 } }
);
...
}
看起來您的數據結構對應於以下類型接口:
interface MyDataReponse {
users: {
nodes: {
id: string; // maybe this is number in your case
firstName:string;
lastName: string;
phoneNumber: string;
email: string;
}[]
}
}
然后在您的數據上:
.then(({ data }: ExecutionResult<{data:MyDataReponse;}>) => {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.