1

I am declaring a typescript variable as follows:

let foo: any = this.someFunc(someArg);

someFunc is a function whose return type matches foo's type:

public someFunc(arg: any): any {
    return {};
}

The return type is 'any' but it also could have been any other type.

Given that foo declaration may have been expressed without specifying the type:

let foo = this.someFunc(someArg);

Should the first declaration example be considered wrong or an error?

I am currently being told in a pull request that this is wrong because it constitutes a repetition.

In my view both uses are fine, the first one is more readable and enforces the return type which is assigned to the declared variable.

In typescript code samples I have seen both notations.

2 Answers 2

1

It's a stylistic choice that your team has to make.

Yes, it's repetition since it can be inferred by the compiler; however, it can be easier to write them in for developers to know without having to go clicking through a number of functions (since someFunc could be inferring its type from something else).

// The compiler knows that a is a number, developers will have to look 
// inside someFunc and otherFunc to know that
const a = someFunc();
function someFunc() {
   return otherFunc();
}
function otherFunc(){
    return 1;
}

Additionaly, if you make a mistake, the compiler will tell you so the repetition of type information is not as bad as duplicating actual code.

FWIW, my team has decided to type everything so we don't have to keep making calls on when to type something. The only exception is when initializing a field/variable with new, and you don't need the type to be some super class/interface.

Sign up to request clarification or add additional context in comments.

Comments

1

The compiler infers the type of foo based on the return type of the function which is why you do not need to explicitly specify it.

It's not wrong nor is it an error to specify it, it is just more verbose.
Some people prefer this verbose way because it is more readable, and some think that it's redundant.

You will need to figure out what are your conventions in your team and work based on that.

In some situations it makes more sense to use it though, for example:

interface A {
    x: number;
}

interface B extends A {
    y: number;
}

function fn(): B { return null }

let a: A = fn();

1 Comment

It's not required because you can have a as B and it will be just the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.