jay
jay

Reputation: 1175

dynamic parameter type for typescript that similar to javascript var

in javascript i can do the following

function testing(someObject){
    console.log(someObject.property1);
    console.log(someObject.property2);
    console.log(someObject.property3);
}

I want to perform something similar in typescript for SomeObject parameter. I can't be bothered to declare a class. I just want to have a dynamic parameter

i tried the following but not working. It does not want to accept any as paraeter type. can someone please advise? perhaps what kind of parameter type that I need to use? thanks.

export class testing{
    test(someObject: Any){

    }
}

Upvotes: 1

Views: 59

Answers (1)

SrAxi
SrAxi

Reputation: 20015

Declare like this:

export class Testing{
    test(someObject: any){
       console.log(someObject);
    }
}

You were right, you just missed the lowercase.

This is an example of a very common method used in Angular/TypeScript:

private handleError(error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
}

If you see, error is a parameter that then gets navigated by the logic within the method. This example is the most used method to handle errors in Http calls.

Upvotes: 1

Related Questions