Gullu
Gullu

Reputation: 3529

typescript undefined variable fundamental

Recently moved from C# to TypeScript. Below code works fine and no errors. However I suspect I have not understood some TS fundamental since we just define interfaces and use them like objects/classes. What is the correct way to declare a variable of a type that is defined in an interface and then assign that variable to its own typed object.

let tempCompany = Company|undefined; 
// I get error if I remove undefined in above line.
// Company is an interface with many properties
tempCompany = this.someArrayOfCompanies.find(x => x.zipCode === 65432);
if (tempCompany !== undefined) { 
    // error if I do not do this if check in above line
    console.log(tempCompany.SalesFigure);
}

Update: Possible answer based on feedback below. For newbies like me moving to TS from .Net/C# the confusion arises because in C# we name interfaces like IAnimal() and then have a class called Dog that implements IAnimal(). In TS we have the Animal interface (without the I) which is named so for TS intellisense to work in vs code. Additional when you api get in Angular it returns a observable list of type Animal. Basically TS is better than JS but still there is all this crazy stuff.

Upvotes: 5

Views: 6640

Answers (2)

Aragorn
Aragorn

Reputation: 5289

Define a variable of type Company like this:

let tempCompany: Company;

Assigning object, what you have would work, as long as the object aligns to the interface:

tempCompany = this.someArrayOfCompanies.find(x => x.zipCode === 65432);

Upvotes: 1

Karl Johan Vallner
Karl Johan Vallner

Reputation: 4310

Maybe this small example will clear things up for you.

interface Animal {
    legs: number;
}

var dog: Dog = { legs: 4 };

type canine = typeof dog;

Upvotes: 2

Related Questions