DEV Community

Discussion on: My confusions about TypeScript

Collapse
 
trusktr profile image
Joe Pea

This doesn't have to do with classes vs functions. If you have a place that accepts string type values, then later you're trying to pass something that is of type string | string[], that's simply wrong and TS is doing a good job telling you that this is a problem. You might know what you're passing, but the next developer, and the next one after that, won't know. This is about scaling code bases in a way that prevents accidents, classes or not.

Collapse
 
kenbellows profile image
Ken Bellows

@trusktr Which thing are you referencing? This is a pretty long thread at this point lol

Collapse
 
trusktr profile image
Joe Pea • Edited

To understand this more specifically, if someone write some piece of code that accepts objects of type Model based on the above class in the article, f.e. some code like

let array: Model[] = []
// push some models into the array, including Animal
// instances, then later:
const col: string = array[2].idColumn
Enter fullscreen mode Exit fullscreen mode

this code is going to fail if it unexpectedly receives string | string[] because it is expecting to have a string only, and may call string-specific methods on that string, etc.

As you can see here, this doesn't have to do with classes vs functions at all. Definitely use only functions if you like that, but this problem still needs to be taken into account, and it is simply about assignment.