Depending on the use case, there are various methods available. Explore different TypeScript methods here
We somehow incorporated
type fInterface = (...params: fArgs) => fRet
type fArgs = [number, string]
type fRet = boolean
No matter – they can be interchanged with Parameters
and ReturnType
If we implemented a function incorrectly
function nop() {}
- Manually selecting parameter types
function isEqual0(x: fArgs[0], y: fArgs[1]): fRet {
//return x == y //TS-ERROR: This condition will always return 'false' since the types 'number' and 'string' have no overlap.ts(2367)
return `${x}` == y
}
- Using destructuring
function isEqual1(...args: fArgs): fRet {
const [x, y] = args
return `${x}` == y
}
- Employing overload. Strict usage, but all parameters are of type
any
during implementation.
function isEqual2(...args: Parameters<fInterface>): ReturnType<fInterface>
function isEqual2(x: any, y: any) {
return x == y
}
- Validation through re-typing (like typing-the-function). There will also be type validation in the parent module regardless.
function isEqual3(x: any, y: any) {
const valid: typeof isEqual3 extends fInterface ? true : never = true
if (!valid)
throw Error()
return x == y
}
const _exports = {
isEqual0, isEqual1, isEqual2, isEqual3, nop
}
, _exportCheck = _exports as Record<keyof typeof _exports, fInterface>
...
There are multiple ways to encounter TS-Error if something goes wrong with the implementation.