Press Space neo
Originally by BAS (Basarat Ali Syed) / @basarat
interface fooInterface{
// constructor
new (fooParam1:number,fooParam2?):number;
// call signature callable without new
(fooParam1:any):string;
// indexable
[index:string]:number;
}
interface fooInterface{
// functions with overloads
fooFunc1(fooParam1:bool):any;
fooFunc2(...fooParam1:number[]):any;
fooFunc3:(fooParam1:bool)=>any;
// variables
fooVar1:number;
fooVar2?:Array;
// array
fooArr1:{
[index:string]:number;
};
fooArr2:number[];
}
interface foo{
x:number;
}
interface foo{
y:number;
}
var bar:foo = {
x:123,
y:123
}
var x:number;
var y:string;
var z:number[];
var foo:{a:any;b:()=>any;} // powerful inline declaration
var __varname__: {
__membername__ : __membertype__ ;
__membername__ : __membertype__ ;
// Repeat
}
var x:{
() : Function;
[foo:string]: number;
new() : string;
}
// interface / inline interface implementation
interface fooInterface{
simpleSyntax():void;
lambdaSyntax:()=>void;
}
var fooInline:{
simpleSyntax():void;
lambdaSyntax:()=>void;
}
// Simple function, When declaring a var or function arguments
var x1 : (s: string)=>string;
// When saying something is callable
var x2 : { (s: string): string; }
interface x3{
(s:string):string;
}
// Errors:
var y1 : (s: string):string;
var y2: { (s: string)=> string; }
interface y3{
(s:string)=>string;
}
var x = 123;
var y;
y = 123;
x = "asdf";
y = "asdf";
var z={foo:123}
var x:any;
var y:number = x;
x = y;
var x = null;
var y = undefined;
var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined
var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object
var obj:String = "123";
var primitive:string = "123";
obj=primitive; // exactly what the first line is doing
primitive=obj; // Error
The magical keyword is declare.
Generate no code whatsoever so obviously
declare var angular;
declare function foo(takes:string):number;
declare class Fancy{
notMuch:string;
}
function foo(req:string,optional?:number){}
Effectively optional. Can even do expressions
function foo( req:string, def:number=3, optional=req+def ) { }
function foo(req, def, optional) {
if (typeof def === "undefined") { def = 3; }
if (typeof optional === "undefined") { optional = req + def; }
}
params denoted by ...
function foo(req:string,...blabla:any[]){}
function foo(req) {
var blabla = [];
for (var _i = 0; _i < (arguments.length - 1); _i++) {
blabla[_i] = arguments[_i + 1];
}
}
interface IFoo{
test(x:string);
test(x:number);
}
class Foo implements IFoo {
test(x: string);
test(x: number);
test(x: any) {
if (typeof x === "string") {
//string code
} else {
//number code
}
}
}
function f():number; // Error
function f(x:any):any{
}
function g():number; // Okay
function g(x?:any):any{
}
// global or module
function simpleSyntax():void{}
var lambdaSyntax1=():void=>{}
// class , basically remove function or var
class fooClass{
simpleSyntax():void{}
lambdaSyntax=():void=>{}
}
// object literal
var fooObject={
simpleSytax: function():void{},
lambdaSyntax: ():void=>{}
}
// Reminder the lambda based signature was a bit different:
// lambdaSyntax:()=>void;
class Foo{
public member:number;
static stat:number = 123;
constructor(){this.member = 123;}
func(){
this.member = 256;
}
}
var Foo = (function () {
function Foo() {
this.member = 123;
}
Foo.stat = 123;
Foo.prototype.func = function () {
this.member = 256;
};
return Foo;
})();
class Foo{
constructor(public member){this.member = 123;}
func(){
this.member = 256;
}
}
class Foo{
public member:number;
}
var Foo = (function () {
function Foo() { }
return Foo;
})();
interface iFoo{
x:number;
}
class Foo1 implements iFoo{
x:number;
}
class Foo2{
x:number;
}
var la:iFoo;
la = new Foo1();
la = new Foo2();
Not everthing that can be declared in an interface can be implemented by a Typescript class e.g. Indexible, call signatures
interface WidgetMap {
[name: string]: Widget;
}
var map: WidgetMap = {};
map['gear'] = new GearWidget();
var w = map['gear']; // w is inferred to type Widget
Callable example
interface Foo {
(): any;
(value: any): void;
}
function createFoo(): Foo {
var getFunc = () => { console.log("get"); return "foo"; }
var setFunc = (value: any) => { console.log("set"); }
return (value?: any) => {
if (value) {
setFunc(value);
} else {
return getFunc();
}
}
}
var f = createFoo();
f("bar");
f();
interface foo{
x?:number;
}
class boo1 implements foo{
}
class boo2 implements foo{
x:number;
}
class FooBase{
}
class FooChild extends FooBase{
}
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var FooBase = (function () {
function FooBase() { }
return FooBase;
})();
var FooChild = (function (_super) {
__extends(FooChild, _super);
function FooChild() {
_super.apply(this, arguments);
}
return FooChild;
})(FooBase);
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var __extends = this.__extends || function(d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function f() { this.constructor = d; }
f.prototype = b.prototype;
d.prototype = new f();
}
class base {
test(foo:number){
console.log(foo);
}
}
class child extends base{
constructor(public x:number){
super();
super.test(x); // 15
this.test(x); // 25
}
test(foo:number){
console.log(foo+10);
}
}
var test=new child(15);
function child(x) {
_super.call(this);
this.x = x;
_super.prototype.test.call(this, x);
this.test(x);
}
class A{
fooMem=10;
}
class B extends A{
constructor(){
console.log(this.fooMem); // undefined
super();
console.log(this.fooMem);
console.log(super.fooMem); // undefined
}
};
var test = new B();
Typescript knows. But doesn't mean it will save you.
class Example{
member = 10;
constructor(){
// Could have been an jquery call
// you were porting from js
setTimeout(function() {
alert(this.member);
},100);
}
}
var ex = new Example();
// all of these are the same
var test1=(x:number)=>{return x*10};
var test2=(x:number)=>(x*10);
var test3=(x:number)=>x*10;
var test4=(x)=>x*10;
var test5=x=>x*10;
// {} require a return statement
// This is actually returning undefined
// which is a valid number and fails silently
var test6=(x:number)=>{x*10};
var foo = () => {return this;}
var _this = this;
var foo = function () {
return _this;
};
class Example{
member = 10;
constructor(){
// Could have been an jquery call
// you were porting from js
setTimeout(()=>{
alert(this.member);
},100);
}
}
var ex = new Example();
Keep functions for:
class Example{
func1:(number)=>void;
func2:()=>number;
member:number = 10;
constructor(){
this.func1=(x)=>{this.member=x};
this.func2=()=>this.member;
}
}
module M{
var s = "test"
export function f(){
return s;
}
}
// Generated
var M;
(function (M) {
var s = "test";
function f() {
return s;
}
M.f = f;
})(M || (M = {}));
module M{
export var s = "test"
}
module M{
export var n = 123;
}
var M;
(function (M) {
M.s = "test";
})(M || (M = {}));
var M;
(function (M) {
M.n = 123;
})(M || (M = {}));
module A.B.C{
}
// same as
module A{
export module B{
export module C{
}
}
}
module x.y.z{
export var n =10;
}
// Alias
import foo = x.y.z;
console.log(foo.n);
var foo = x.y.z;
console.log(foo.n);
module Test{
export class Test{
}
}
var Test;
(function (Test) {
var Test = (function () {
function Test() { }
return Test;
})();
Test.Test = Test;
})(Test || (Test = {}));
module M
{
export interface P {}
}
import im = M;
var foo1:im.P; // Okay
var vm = M;
var foo2:vm.P; // Error
interface iFoo{
x:number;
}
class Foo1 implements iFoo{
x:number;
}
class Foo2{
x:number;
}
var la:iFoo;
la = new Foo1();
la = new Foo2();
var fa:Foo1 = new Foo2(); //Error
interface inter{
foo:number;
}
module mod{
export var foo:number;
}
var w:inter;
var x:mod;
var y:{foo:number;}
var z={foo:123}
w=x=y=z;
z=y=x=w;
interface inter{
foo:number;
}
var x:inter;
var y={
foo:123,
la:23
};
x = y;
y = x; //Error
Present in lib.d.ts that ships with the typescript compiler.
interface Array {
toString(): string;
toLocaleString(): string;
concat(...items: _element[][]): _element[];
concat(...items: _element[]): _element[];
join(seperator?: string): string;
interface Array {
shuffle: () => any; // <-- Whatever signature you want.
}
Array.prototype.shuffle = function () { ... };
// error
var x:HTMLCanvasElement = document.getElementById("canvasId");
// valid
var y:HTMLCanvasElement =
< HTMLCanvasElement > document.getElementById("canvasId");
// type inferred
var z =
< HTMLCanvasElement > document.getElementById("canvasId");
declare var $: any;
declare var $: JQueryStatic;
interface JQueryStatic {
// AJAX
ajax(...params:any[]);
declare var $: JQueryStatic;
interface JQueryStatic {
// AJAX
ajax(settings: JQueryAjaxSettings);
ajax(url: string, settings: JQueryAjaxSettings);
interface JQueryAjaxSettings {
accepts?: any;
async?: bool;
beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings);
cache?: bool;
interface JQueryStatic {
// More traditional members: Callables
(selector: string, context?: any): JQuery;
(element: Element): JQuery;
(object: {}): JQuery;
(elementArray: Element[]): JQuery;
(object: JQuery): JQuery;
(func: Function): JQuery;
(): JQuery;
interface JQuery {
attr(attributeName: string): string;
attr(attributeName: string, value: any): JQuery;
html(htmlString: string): JQuery;
html(): string;
interface JQuery {
myPlugin(): JQuery;
}
.fadeToggle( [duration ] [, easing ] [, complete ] )
fadeToggle(duration?: any, callback?: any): JQuery;
fadeToggle(duration?: any, easing?: string, callback?: any): JQuery;
class Test{
static foo = 123;
bar = 456;
}
declare class Test {
static foo: number;
public bar: number;
}
// Non static members
interface Test{
bar:number;
}
// Static members and constructors go here:
interface TestStatic {
new():Test;
foo:number;
}
declare var Test:TestStatic;