1

I have a class that has some pretty complicated types based on the generics passed to the class. I use these same types in a few places and I'm trying to figure out how to make them reusable:

class Foo<T> {
  method(): SomeComplicateType<T> {}
  method2(): SomeComplicateType<T> {}
}

The only thing I can come up with is this, but it allows the user to overwrite the type which I don't want:

class Foo<T, U=SomeComplicatedType<T>> {
  method(): U {}
  method2(): U {}
}
1
  • 2
    This is discussed in Microsoft/TypeScript#7061; there's no official solution but there are several workarounds in there... Commented Jun 4, 2019 at 1:26

2 Answers 2

1

TypeScript doesn't allow type creation between the two scopes:

class A<Scope1> {
  x():Scope2;
}

Your solution

What you have found is a way to create it as a chain in Scope1.

Thoughts

Personally I would bite the bullet and not try to create a new type. I prefer explicit work whenever possible.

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

Comments

0

Sorry for this obvious suggestion but you could use an alias:

type NiceName<T> = SomeComplicateType<T>

class Foo<T> {
  method(): NiceName<T> {}
  method2(): NiceName<T> {}
}

1 Comment

No suggestions are bad :) This does make it a bit better and is what I have now, but it's still not the best writing NiceName<BLAH, FOO, BAR, BAZ> (I don't like T, U, V in this case since I can barely follow the logic, lol)

Your Answer

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