How Do I Add A Static Method To My Typescript Class?
Solution 1:
Option 1: export a function directly on the Api module
You can export
a function
on the Api
module to retrieve/create a User
instance:
moduleApi
{
exportclassUser
{
}
exportfunctionGetUser(id: number):User {
returnnewUser();
}
// or a slightly different syntax (which generates different JavaScript):exportvarDelete = (id: number) => {
};
}
You can't have the class named User
and the function
also be User
, so I've changed it to GetUser
in the example.
You could then call:
Api.GetUser(1234)
or
Api.Delete(1234);
Option 2: Using an interface
You could also approach this by using an interface if you wanted to limit the ability of
calling code from being able to instantiate instances of the inner class by using an interface instead. Below I've created a simple ISuperUser
interface and and implementation of the class called SuperUserImpl
. As the SuperUserImpl
isn't exported, it's not publicly creatable. This is nice in that you could use simple Api.SuperUser(2345)
to return new instances of a class that implements the ISuperUser
interface.
moduleApi {
exportinterface ISuperUser {
id: Number;
name: String;
}
classSuperUserImplimplements ISuperUser
{
constructor(public id: Number) {
}
publicname: String;
}
exportvarSuperUser = (id:Number):ISuperUser => {
returnnewSuperUserImpl(id);
}
}
var su : Api.ISuperUser = Api.SuperUser(5432);
alert(su.id);
Option 3: JavaScript and instanceof
There's a trick that is often used in JavaScript class constructor wherein the function
/constructor for a new object checks to see whether it is of the right type (was the function called or created), and if not created, returns a new instance:
if (!(thisinstanceof User)) {
returnnewUser(id);
}
While correct, TypeScript when trying to call a constructor with that will cause a compiler warning. This will work, but with the compiler warning:
constructor(id: Number) {
if (!(thisinstanceofUser)) {
returnnewUser(id);
}
}
And later calling:
var u: Api.User = Api.User(543);
A compiler warning suggests, "did you forget to use 'new'?" It does produce valid JavaScript, just with a warning. I'd probably go with the static-like method approach to avoid the TypeScript compiler warning.
Post a Comment for "How Do I Add A Static Method To My Typescript Class?"