Home > OS >  How to return the `any` type what is I need when used `keyof`?
How to return the `any` type what is I need when used `keyof`?

Time:10-20

I don't know how to describe this question right, so please see the belows code

interface TestParams<T> {
  order?: keyof T
  attr1?: number
  attr2?: string
}

async function Test<T = any>(_obj: TestParams<T>): Promise<T> {
  return {} as T
}
Test({ order: 'id2' })

// function Test<{
//     id2: any;
// }>(_obj: TestParams<{
//     id2: any;
// }>): Promise<{
//     id2: any;
// }>

Why the T type is { id2: any; } instead of any

The belows is my needs type

function Test<any>(_obj: TestParams<any>): Promise<PostgrestResponse<any>>

typescript playground

Update

new playground

Update

I added U which is keyof T, then implement my needs

interface TestParams<T> {
  order?: T
  attr1?: number
  attr2?: string
}

async function test<T = any, U = keyof T>(_obj: TestParams<T extends undefined ? string : U>): Promise<T> {
  return {} as T
}

test({ order: 'id2' })
// The belows type is what I needed
// function test<any>(_obj: TestParams<"id2">): Promise<any>

interface TestType {
  id2: number
  id3: number
}
test<TestType>({ order: 'id2' })

playground

CodePudding user response:

If { order: 'id2' } is a TestParams<T> then, because order is keyof T, your T must be an interface that has a id2 property. There is no restriction on the property's type, so it has to be any.

Thus, T is an interface with an id2 property of any value. That's why T is { id2: any; }.

CodePudding user response:

You're missing a generic constraint on U so TypeScript can't infer what string you gave to TestParams:

async function test<T = any, U extends keyof T = keyof T>(_obj: TestParams<U>): Promise<T> {
//                             ^^^^^^^^^^^^^^^
  return {} as T
}

Playground

  • Related