typescript elegantly enforce a constraint while preserving types

前端 未结 2 626
Happy的楠姐
Happy的楠姐 2021-01-26 08:47

so originally to enforce a constraint, i\'d just apply an interface like this

// this is the constraint
interface Topic {
  [key: string]: (...args: any[]) =>          


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-26 09:32

    One option is to use a no-op function that has the relevant generics in the argument so it constrains in place:

    (playground)

    // this is the constraint
    interface Topic {
      [key: string]: (...args: any[]) => Promise
    }
    function ensureTopic(topic: T){
        return topic;
    }
    
    // object that must pass the constraint
    const topic = ensureTopic({
    
      // GOOD: topic methods must conform
      async actuate(a: boolean) {}
    })
    

    related: Use function interface to ensure parameters but infer more specific return type

提交回复
热议问题