TypeScript
Lit Query 使用 TypeScript 编写,并复用 TanStack Query Core 的类型系统。最重要的规则与所有其他适配器一致:为你的查询函数和修改函数明确定义返回类型,结果访问器将据此自动推断类型。
在 tsconfig.json 中将 useDefineForClassFields 设为 false,以确保作为类字段初始化的响应式属性持续触发更新。详情请参阅 Requirements。
查询推断
TypeScript
1import { LitElement } from 'lit'2import { createQueryController } from '@tanstack/lit-query'3 4type Todo = {5 id: number6 title: string7}8 9async function fetchTodos(): Promise<Todo[]> {10 const response = await fetch('/api/todos')11 if (!response.ok) throw new Error('Failed to fetch todos')12 return response.json() as Promise<Todo[]>13}14 15class TodosView extends LitElement {16 private readonly todos = createQueryController(this, {17 queryKey: ['todos'],18 queryFn: fetchTodos,19 })20 21 render() {22 const query = this.todos()23 // query.data is Todo[] | undefined until success is known.24 }25}检查 isSuccess、isPending、isError 或 status 会像 TanStack Query Core 的结果类型一样,对结果类型进行精确限定:
TypeScript
1const query = this.todos()2 3if (query.isSuccess) {4 query.data5 // Todo[]6}修改推断
TypeScript
1import { LitElement } from 'lit'2import { createMutationController } from '@tanstack/lit-query'3 4type CreateTodoInput = {5 title: string6}7 8type Todo = {9 id: number10 title: string11}12 13async function addTodo(input: CreateTodoInput): Promise<Todo> {14 const response = await fetch('/api/todos', {15 method: 'POST',16 body: JSON.stringify(input),17 })18 if (!response.ok) throw new Error('Failed to create todo')19 return response.json() as Promise<Todo>20}21 22class AddTodoButton extends LitElement {23 private readonly mutation = createMutationController(this, {24 mutationFn: addTodo,25 })26 27 private add() {28 this.mutation.mutate({ title: 'Learn Lit Query' })29 }30}提取选项类型
当你希望在控制器与 QueryClient 调用之间共享类型化的选项时,可使用 queryOptions、infiniteQueryOptions 和 mutationOptions。
TypeScript
1import { LitElement } from 'lit'2import {3 QueryClient,4 createQueryController,5 noop,6 queryOptions,7} from '@tanstack/lit-query'8 9function todosOptions() {10 return queryOptions({11 queryKey: ['todos'],12 queryFn: fetchTodos,13 staleTime: 5 * 1000,14 })15}16 17const queryClient = new QueryClient()18 19class TodosView extends LitElement {20 private readonly todos = createQueryController(this, todosOptions())21}22 23void queryClient.query(todosOptions()).catch(noop)由 queryOptions 返回的带品牌(branded)的 queryKey 还有助于 queryClient.getQueryData 等 API 理解数据类型。
全局注册类型
由于 @tanstack/lit-query 重新导出了 TanStack Query Core,Lit 应用中的模块增强(module augmentation)需针对 @tanstack/lit-query 编写:
TypeScript
1import '@tanstack/lit-query'2 3type AppQueryKey = ['todos' | 'projects', ...ReadonlyArray<unknown>]4 5declare module '@tanstack/lit-query' {6 interface Register {7 queryKey: AppQueryKey8 mutationKey: AppQueryKey9 }10}请参阅自动生成的参考文档,了解 Lit 特有的 option and result types。