45

Can you define generics with safe types, as you can with c#?

E.g.

public bool Foo<T>() where T : struct { /* */ }

Typescript now has generics, but can I perform a similar action?

Thanks.

2 Answers 2

104

Ok it seems you can do this:

Foo<T extends IBar>() { /* */ }

And that seems to make all calls require the T to implement IBar.

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

+1 - spot on. This is taken from the Java implementation of generics - the extends keyword is used to constrain to either an interface or a class.
But it seems it does not enforce anything yet.
Note that if you want to constrain by interfaces, you use the extends keyword rather than the implements on. For example Foo<T extends IBar>.
Note that it's not required for a type to "implement" the IBar interface, it must merely be compatible with it.
0

If you don't want to create an extra class/interface, you can, for example, do the following:

Foo<T extends{ id: string | number }>

Comments

Your Answer

Draft saved
Draft discarded

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.