TypeScript
Lit Query는 TypeScript로 작성되었으며 TanStack Query Core의 타입 시스템을 재사용합니다. 가장 중요한 규칙은 다른 모든 어댑터와 동일합니다. 쿼리 및 뮤테이션 함수에 명확히 정의된 반환 타입을 지정하면 결과 접근자가 이를 바탕으로 타입을 추론합니다.
쿼리 추론
import { LitElement } from 'lit'
import { createQueryController } from '@tanstack/lit-query'
type Todo = {
id: number
title: string
}
async function fetchTodos(): Promise<Todo[]> {
const response = await fetch('/api/todos')
if (!response.ok) throw new Error('Failed to fetch todos')
return response.json() as Promise<Todo[]>
}
class TodosView extends LitElement {
private readonly todos = createQueryController(this, {
queryKey: ['todos'],
queryFn: fetchTodos,
})
render() {
const query = this.todos()
// query.data is Todo[] | undefined until success is known.
}
}
isSuccess, isPending, isError 또는 status를 확인하면 TanStack Query Core 결과 타입과 마찬가지로 결과 타입이 좁혀집니다:
const query = this.todos()
if (query.isSuccess) {
query.data
// Todo[]
}
뮤테이션 추론
import { LitElement } from 'lit'
import { createMutationController } from '@tanstack/lit-query'
type CreateTodoInput = {
title: string
}
type Todo = {
id: number
title: string
}
async function addTodo(input: CreateTodoInput): Promise<Todo> {
const response = await fetch('/api/todos', {
method: 'POST',
body: JSON.stringify(input),
})
if (!response.ok) throw new Error('Failed to create todo')
return response.json() as Promise<Todo>
}
class AddTodoButton extends LitElement {
private readonly mutation = createMutationController(this, {
mutationFn: addTodo,
})
private add() {
this.mutation.mutate({ title: 'Learn Lit Query' })
}
}
옵션 추출하기
컨트롤러와 QueryClient 호출 간에 타입이 지정된 옵션을 공유하려면 queryOptions, infiniteQueryOptions 및 mutationOptions를 사용합니다.
import { LitElement } from 'lit'
import {
QueryClient,
createQueryController,
noop,
queryOptions,
} from '@tanstack/lit-query'
function todosOptions() {
return queryOptions({
queryKey: ['todos'],
queryFn: fetchTodos,
staleTime: 5_000,
})
}
const queryClient = new QueryClient()
class TodosView extends LitElement {
private readonly todos = createQueryController(this, todosOptions())
}
void queryClient.query(todosOptions()).catch(noop)
queryOptions에서 반환된 브랜드가 지정된 queryKey는 queryClient.getQueryData 같은 API가 데이터 타입을 이해하는 데도 도움이 됩니다.
전역 등록 타입
@tanstack/lit-query가 TanStack Query Core를 다시 export하므로 Lit 앱에서는 @tanstack/lit-query를 대상으로 모듈 확장을 작성합니다:
import '@tanstack/lit-query'
type AppQueryKey = ['todos' | 'projects', ...ReadonlyArray<unknown>]
declare module '@tanstack/lit-query' {
interface Register {
queryKey: AppQueryKey
mutationKey: AppQueryKey
}
}
Lit 전용 옵션 및 결과 타입은 생성된 레퍼런스를 참조하세요.