Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

definition file: multiple possible types for property

Tags:

typescript

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() );
like image 755
user247702 Avatar asked Jul 12 '13 12:07

user247702


3 Answers

Typescript 1.4 now supports union types

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

like image 126
Simon_Weaver Avatar answered Oct 21 '22 08:10

Simon_Weaver


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:

  1. Function overloading
  2. Generics

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.

like image 21
musically_ut Avatar answered Oct 21 '22 10:10

musically_ut


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.

like image 30
Jeffery Grajkowski Avatar answered Oct 21 '22 10:10

Jeffery Grajkowski