any
. Authors of typing files ( .d.ts
) can also use these features to describe external libraries. Those who follow the development of the compiler may have noticed that we ourselves also use them.
string
or string[]
. Now you can write this:
interface RunOptions { program: string; commandline: string[]|string; }
var opts: RunOptions = /* ... */; opts.commandline = '-hello world'; // OK opts.commandline = ['-hello', 'world']; // OK opts.commandline = [42]; // : number string string[]
if(opts.commandline.length === 0) { // string string[] length console.log("!"); }
function formatCommandline(c: string[]|string) { if(typeof c === 'string') { return c.trim(); } else { return c.join(' '); } }
typeof
or instanceof
operators to determine the type of a value at runtime. Typescript now understands these constructs and uses them when inferring a type, if they are used in the condition block:
var x: any = /* ... */; if(typeof x === 'string') { console.log(x.subtr(1)); // : 'string' 'subtr' } // 'x' 'any' x.unknown(); // OK
instanceof
can be used with classes and combined types:
class Dog { woof() { } } class Cat { meow() { } } var pet: Dog|Cat = /* ... */; if(pet instanceof Dog) { pet.woof(); // OK } else { pet.woof(); // Error }
function equal<T>(lhs: T, rhs: T): boolean { return lhs === rhs; } // : // : - 'number' 'string' var e = equal(42, 'hello');
var x = [1, 'world']; // x: Array<string|number> x[0] = 'hello'; // OK x[0] = false; // - 'boolean' 'number', 'string'
type
keyword:
type PrimitiveArray = Array<string|number|boolean>; type MyNumber = number; type NgScope = ng.IScope; type Callback = () => void;
master
branch from the Typescript repository on Github , try it and share with us.
// : [number, string] // : Array<string|number> var x = [1, 'world'];
var x = [dog, cat, animal]; // 'x' 'Animal[]' x[0] = new Frog();
x
were displayed as a tuple [Dog, Cat, Animal]
, then the assignment in the second line would cause an error. The authors considered it more correct to require explicit indication of tuples, and this sounds rather logical.
var x : [number, string] = [1, "test"]; var y : Array<number|string> = x; // x = y; // :
Source: https://habr.com/ru/post/245109/