Samantha J T Star
Samantha J T Star

Reputation: 32778

How can I define an object to have different fields using typescript?

I have the following function:

function getAdminParams(entity) {
   params = {};
   params = {
                pk: "0006000",
                param: "?pk=0006000",
                table: "Content",
                success: true
            };
  return params;
}

In another file I use this function like this:

params = getAdminParams(entity);
    if (params.success) {

Is there a way that I could use intellisense so that the params object shows as having a "success" parameter? I saw that Typescript has classes and interfaces but I am not sure how or if I can use these as a return type.

Upvotes: 1

Views: 608

Answers (1)

Jude Fisher
Jude Fisher

Reputation: 11294

If you define params as an interface, then you can use a colon after the function parentheses to declare it as the return type of getAdminParams(). Like this:

interface IParams {
    success: bool;
    pk: string;
    // etc...
}

function getAdminParams(entity): IParams {
    params = {
                pk: "0006000",
                success: true
                // etc...
            };
    return params; // If the properties assigned do not fulfill the IParams interface, this will be marked as an error.
}

params = getAdminParams(entity);
if (params. // Intellisense should offer success and pk and any other properties of IParams).

Within getAdminParams you could explicitly declare params as a new IParams, but type inference will set up the intellisense for you even if you don't, as long as the properties you assign to the params object fulfill the contract specified in the IParams interface.

Of course your return type could be a class, or a string, or any other type, and you would declare that using the function f(): returnType syntax in just the same way.

The language specification covers all of this in great detail, or there is a shorter introduction here: http://www.codeproject.com/Articles/469280/An-introduction-to-Type-Script or a similar SO question here: How to declare Return Types for Functions in TypeScript

Upvotes: 2

Related Questions