Closed
Description
Search Terms
type of function's parameters list; type of arguments list; tuples;
Suggestion
There are functions a()
and b()
. Function a()
have the same signature (parameters) as function b()
.
Instead of manually copying list of parameters with their types from b()
to a()
, there should be a way to assign types of parameters to a()
from b()
.
function a(...args: /* possible syntax starts */ parametersof b /*possible syntax ends*/ ) {
b(...args)
}
function b (a: string, b: number) { /* ... */}
a('foo', 1) // ok
a('foo', 'bar') // compiler error "Argument of type 'bar' is not assignable to parameter of type 'number'"
parametersof ...
should probably return a tuple.
Related question on Stackoverflow
Use Cases
- Decorators or simply reusing existing functions:
function a(...args: parametersof b) {
// ... do some stuff
b(...args)
}
- API that provides lazy-loaded functions or provides functions based on environment:
import someFunc from './someFunc'
export const someAPI = {
someFunc, // normal one, we just re-exporting this func
async lazyFunc(...args: parametersof eagerFunc) {
const {eagerFunc} = await import('./eagerFunc')
return eagerFunc(...args)
}, // lazy func. helps to reduce main bundle
get node() {
if (runningInNode()) {
return {
async nodeFunc(...args: parametersof nodeFunc) {
const {nodeFunc} = await import('./nodeFunc')
return nodeFunc(...args)
}
}
}
} // here we do not add code, that is supposed to work only in node.js, to frontend bundle)
}
Current workarounds and their faults
function a(a: string, b: number) {
b(...args)
}
function b (a: string, b: number) {/*...*/}
Above practice have these disadvantages:
- When changing
b
's signature, we also have to changea
's one. That is little bit harder maintenance and a window for new errors. - Contradicts with DRY principle
Comparison to tuples
I am aware of new "tuples" feature in TS 3.0, which is great! However using tuples for this use case requires creating new types, while "parametersof" solution will end up in minimum possible amount of code and maximum readability.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript / JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. new expression-level syntax)