DEV Community

Discussion on: My confusions about TypeScript

Collapse
 
ronnewcomb profile image
Ron Newcomb • Edited

1)

function handleRelations<T extends Model>(modelClass: T) {

Look up Generics Constraints in the typescript manual.

2) That's not a Typecript question, that's an object-oriented question. The answer is "you can't, and shouldn't".

If I have an Animal[] and .map it to call a function on each return value...
animals.map(a => a.idColumn().whatIsValidHere)
... then what is always safe for whatisvalidhere if it's sometimes a string sometimes an array sometimes an Invoice, etc.

3)

interface SimpleObject<T> {
  [key: string] : T
}

is a bit more useful. Stick in /shared/ or wherever you keep such things.

Collapse
 
jdforsythe profile image
Jeremy Forsythe

You beat me to it! typeof Model and T extends Model are the useful features here, but I also agree with Edward Tam - you should probably eschew subclassing in general. "Is a" object relationships are the tightest form of coupling that exists. Instead use functions or even mixins, if you must attach "methods" to your objects. You probably don't need a base class when you have interfaces and mixins available to you.

Collapse
 
coly010 profile image
Colum Ferry

is a is strong, but can be loosened with Factories and Bridge Pattern

Thread Thread
 
jdforsythe profile image
Jeremy Forsythe

Haven't found a good use for the Bridge Pattern, but I've often wondered why more ORMs aren't using Factories/mixins