¿Cómo creo declaraciones de clase ambientales en TypeScript?
Estoy tratando de crear un archivo .d.ts para la biblioteca KineticJS. Hasta ahora he creado la siguiente declaración de interfaz "kinect.d.ts".(Recorté un poco el código para StackOverflow pero espero que entiendas la idea)
module Kinetic {
interface Rect extends Shape {
constructor (config) ;
}
interface Shape extends Node
{
}
interface Node {
constructor (config);
clone(attrs): Node;
getAbsoluteOpacity(): number;
getAbsolutePosition(): any;
/*
other methods removed for stackoverflow example
*/
}
}
Esperaba que esto fuera suficiente para poder crear un objeto Kinetic.Rect en mi archivo app.ts
/// <reference path="Kinetic.d.ts" />
var rect = new Kinetic.Rect({
x: 239,
y: 75,
width: 100,
height: 50
});
Pero parece que tengo que hacer un trabajo extra para usar las clases de KineticJS (como Rect) en TypeScript. ¿Alguien podría darme algunas indicaciones sobre cómo lograr esto?
Respuesta #1
¿Has visto la aplicación de ejemplo de TypeScript en: http://typescript.codeplex.com/SourceControl/changeset/view/fe3bc0bfce1f#samples/imageboard/mongodb.ts
El código en este enlace crea una definición para la biblioteca mongodb. Una diferencia entre esto y la respuesta de Sohnee es que Sohnee implementa el constructor en contraste con el siguiente fragmento de código del enlace, que es una clase stub. No tengo suficiente reputación para preguntarle a Sohnee en la respuesta aceptada por qué implementó el constructor para una clase ambiental.
declare module "mongodb" {
export class Server {
constructor(host: string, port: number, opts?: any, moreopts?: any);
}
export class Db {
constructor(databaseName: string, serverConfig: Server);
public open(callback: ()=>void);
Respuesta #2
Aquí está mi ejemplo funcional de cómo crear definiciones de ambiente para tu clase Kinetic:
interface Shape {
x: number;
y: number;
width: number;
height: number;
}
interface IKinetic {
Rect(shape: Shape);
}
declare var Kinetic: IKinetic;
var rect = <Shape> new Kinetic.Rect({
x: 239,
y: 75,
width: 100,
height: 50
});
Tenga en cuenta que he utilizado declare var Kinetic: IKinetic; para decirle a TypeScript que Kinetic es de un tipo particular.
Actualización - Ejemplo 2
interface IShape {
x: number;
y: number;
width: number;
height: number;
}
interface IRect extends IShape {
}
module Kinetic {
export class Rect implements IRect {
public x: number;
public y: number;
public width: number;
public height: number;
constructor(rect: IShape) {
this.x = rect.x;
this.y = rect.y;
this.width = rect.width;
this.height = rect.height;
}
}
}
var rect = new Kinetic.Rect({
x: 239,
y: 75,
width: 100,
height: 50
});
