Home > other >  How to force a type declaration to have at least one known parameter while the rest are unknown
How to force a type declaration to have at least one known parameter while the rest are unknown

Time:06-08

I'm trying to build a function that accepts an object of any shape, but I want to be sure that the object always have a specific property of a given type.

function ofInterest(param: any){
   // do some computation using param's p property
   ... = param.p
}

That way calling function ofInterest with a parameter which does not have the desired property results in a type check error:

const param = {q: '', r: 0}

// this should be an error cause param does not have a property 'p'
ofInterest(param)

How can I declare ofInterest's param?

CodePudding user response:

function ofInterest(param: {p: DesiredType} & any){
   // now we I'm totally sure that property 'p' exists in param
   ... = param.p
}

The trick is to define param as a union between the desired specific type(s) and any. That way we always know that the parameter have the expected property(ies) while we still give the client some freedom to use the function with objects of almost any shape.

CodePudding user response:

You need to use generics in this case:

function ofInterest<Param extends { p:any }>(param: Param){
   param.p // ok
}
  • Related