Search code examples
typescripttypescript-genericsreact-typescript

Typescript's type inference, why can't the type of data be inferred?


According to what I thought, data can infer the type of {list: string[] } and then use data.list , but it doesn't seem to work, and it will give an error when using it. Is there something wrong with where my code is written?

enter image description here

enter image description here

full code

const get = <T, C>(url: string, clearFn: (data: T) => C): Promise<C | null> =>
  new Promise((resolve) => {
    axios
      .get(url)
      .then((result) => {
        resolve(clearFn(result.data.data))
      })
      .catch(() => {
        resolve(null)
      })
  })

function getQuestionList<T = { list: string[] }, C = { list: number[] }>(): Promise<C | null> {
  return get<T, C>('acb/abc', (data): any => {
    console.log(data.list)
    return { list: [1, 2] }
  })
}

Solution

  • You are defining the default value of your generics not what it extends !

    T = { list: string[] } becomes T extends { list: string[] }.

    Full function :

    function getQuestionList<T extends { list: string[] }, C extends { list: number[] }>(): Promise<C | null> {
      return get<T, C>('acb/abc', (data): any => {
        console.log(data.list)
        return { list: [1, 2] }
      })
    }