I'm writing some definitions for an existing JS library (CKEditor). Is it possible to be more specific than toolbar: any
?
Documentation:
toolbar : Array/String
The toolbox (alias toolbar) definition. It is a toolbar name or an array of toolbars (strips), each one being also an array, containing a list of UI items.
Library code:
var toolbar = editor.config.toolbar;
// If it is a string, return the relative "toolbar_name" config.
if ( typeof toolbar == 'string' )
toolbar = editor.config[ 'toolbar_' + toolbar ];
return ( editor.toolbar = toolbar ? populateToolbarConfig( toolbar ) : buildToolbarConfig() );
Of course you still have to check the value inside the function and react accordingly, but now you can get compile time checking without having to change the type to any
.
function f(x: number | number[]) {
if (typeof x === "number") {
return x + 10;
}
else {
// return sum of numbers
}
}
http://blogs.msdn.com/b/typescript/archive/2015/01/16/announcing-typescript-1-4.aspx
Unfortunately, Typescript does not support union types and is unlikely to do so in the near future.
There are two suggestions made in the thread:
In the given piece of code, I cannot see anyway of avoiding the any
type. However, outside the snippet, if the toolbar
argument is being passed as an argument, function overloading might be able to express the type of those.
You could model that the toolbar is an Array and a string.
interface ArrayAndString extends Array, String { }
var toolbar: ArrayAndString = editor.config.toolbar;
That says that both array and string operations are legal, which isn't really true and doesn't give much better safety than any
. There's no way to model that it can be one or the other but not both.
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