Definition file: several possible types for a property

I am writing some definitions for an existing JS library (CKEditor). Is it possible to be more specific than toolbar: any ?

Documentation:

toolbar: array / string

Toolbar definition (aliases). This is the name of the toolbar or an array of toolbars (stripes), each of which is also an array containing a list of user interface elements.

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() ); 
+8
typescript
source share
3 answers

Typescript 1.4 now supports join types

Of course, you still need to check the value inside the function and react accordingly, but now you can get a compile-time check without changing 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

+16
source share

Unfortunately, Typescript does not support union types and is unlikely to do so in the near future .

There are two sentences in the stream:

  • Function overload
  • Generics

In this code snippet I do not see to avoid type any . However, outside the fragment, if the toolbar argument is passed as an argument, the overload function may be able to express the type of these.

+2
source share

You can simulate that the toolbar is an array of Array and .

 interface ArrayAndString extends Array, String { } var toolbar: ArrayAndString = editor.config.toolbar; 

This suggests that array and string operations are legal, which is actually not the case, and does not provide much better security than any . There is no way to simulate the fact that it can be this or that, but not both.

+1
source share

All Articles