Why is typescript ES6 not detecting that objects are not functions?
find: (collection: string, query: object, sortQuery = {}, cb?: Function) => {
socketManager.call('find', collection, query, sortQuery, cb);
}
Based off this function, you would assume that this would fail:
this._services._socket.methods.find('vendors', {type: 'repair'}, (errVen, resVen) => {}
Since there is no sortQuery object but instead a callback function. This is not giving me any type of error and means that typescript is allowing the callback as the object type.
How do I ensure this results in an error?
With TypeScript Conditionals (TS v2.8), we can use Exclude
to exclude Functions
from the object
type using Exclude<T, Function>
:
let v = {
find: <T extends object>(collection: string, query: object, sortQuery: Exclude<T, Function>, cb?: (a: string, b: string) => void) => {
}
}
// Invalid
v.find('vendors', { type: 'repair' }, (a, b) => { })
v.find('vendors', { type: 'repair' }, 'I am a string', (a, b) => { })
// Valid
v.find('vendors', { type: 'repair' }, { dir: -1 })
v.find('vendors', { type: 'repair' }, { dir: -1 }, (a, b) => { })
A default parameter value can then be set like this:
sortQuery: Exclude<T, Function> = <any>{}
As you can see in the image below, errors are thrown for the first two calls to find
, but not the second two calls to find
:
The errors that then display are as follows:
- [ts] Argument of type '(a, b) => void' is not assignable to parameter of type 'never'. [2345]
- [ts] Argument of type '"I am a string"' is not assignable to parameter of type 'object'. [2345]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With