Removing a type assertion with Object.assign in TypeScript
I loathe type assertions in TypeScript. Every as is a spot where I am telling the compiler “trust me”, and every as unknown as is me telling it to stop thinking altogether. So when I found one in an adapter function I w…
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
I loathe type assertions in TypeScript. Every as is a spot where I am telling the compiler “trust me”, and every as unknown as is me telling it to stop thinking altogether. So when I found one in an adapter function I was working on, I wanted to get rid of it. In the process, I learned an interesting fact about how unknown and Object.assign behave together. The Adapter The setup was roughly this: a library exposes a function that takes a client, and that client must have a request function resolving to a Response with a typed json method. On my side, I already had a function that does the request and returns the parsed data directly. I just needed to adapt one to the other. Here is a minimal version of it: type TypedResponse<T> = Omit<Response, 'json'> & {json: () => Promise<T>} type Client = { request: (query: string) => Promise<TypedResponse<{data?: unknown}>> } type FetchData = (query: string) => Promise<unknown> The library only ever calls json() on the response, so my first version just returned an object with that method: export function toClient(fetchData: FetchData): Client { return { request: async (query) => { const data = await fetchData(query) return {json: async () => ({data})} }, } } TypeScript, correctly, doesn’t accept it: Type '{ json: () => Promise<{ data: unknown; }>; }' is not assignable to type 'TypedResponse<{ data?: unknown; }>'. Type '{ json: () => Promise<{ data: unknown; }>; }' is missing the following properties from type 'Omit
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。