Home > front end >  How to solve the problem caused by using the "as" keyword
How to solve the problem caused by using the "as" keyword

Time:11-02

I had this problem Why do I always have to fill in the details


type Doc = Record<string,any>


type DocFilter<T extends Doc> = {[k in keyof T as T[k] extends (()=>void) ? never:k]:T[k]}



const doc1 = {aaaa:'',bbbb:1,c:()=>{}} 


function test1 <T extends Partial< typeof doc1>,>(opt:{prop:T}){}

test1({
  prop:{
    aaaa:'',
    bbbb:1, // When I enter the "bbbb" field, there is a prompt .This was to be expected
  }
})

test2 I want to filter out the function field // Why do I always have to fill in the details

function test2 <T extends Partial<DocFilter< typeof doc1>>,>(opt:{prop:T}){}

test2({
  prop:{
    aaaa:'', // When I enter the first field, the correlation keyword prompts all fields.  For example, enter a to prompt aaaa and b to prompt bbbb  
    b   //But I couldn't get a prompt when I entered the second field .The cause was found because of the ''as' keyword. How to solve this problem?  
  }
})
 

Playground

CodePudding user response:

I'm not really sure why your solution doesn't work, but this other way of defining DocFilter seems to do what you want. Instead of using as to re-map the keys, you can use Omit to exclude the ones you don't want. I borrowed KeysMatching from this other answer.

type KeysMatching<T, V> = {[K in keyof T]: T[K] extends V ? K : never}[keyof T];
type DocFilter<T> = Omit<T, KeysMatching<T, () => void>>

Playground Link

  • Related