3

Is it possible to require a generic type on a function without parameters?

Example:

function myFunc<T>() {
  return {} as T
}

const a = myFunc() // a: unknown

I want to make the generic type required, but couldn't find anything about it.

2
  • Keep in mind that such a function cannot possibly be implemented correctly. Source: twitter.com/SeaRyanC/status/1205170798282960896 Commented Jul 28, 2020 at 19:13
  • Thanks for the info! Yeah, this just works because of the casting but doesn't have any type-safety. Commented Jul 28, 2020 at 19:46

1 Answer 1

3
function myFunc<T>() {
  return {} as T
}

const a = myFunc<SomeObject>() // a:SomeObject

seems to work just fine.

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

5 Comments

That can lead to dangerous code tho. a will be typed as string but will contain a plain object.
yes this work. Bus as I asked, is it possible to make the generic type being required? It's optional, and will infer unknown if no type is provided
apparently it cant infer the type into to const a without you explicitly passing the type you want. check this stackoverflow.com/a/57548987/281474
I check this answer before... On the answer that you provide the type can only be inferred because of the parameter. I don't want any parameters.
you can have a default value for T but that's obviously not the same as requiring a type..

Your Answer

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.