arsis-dev
arsis-dev

Reputation: 453

Typescript required function type argument

I want a function that requires a type parameter be provided:

function foo<T>(key: keyof T): keyof T {
  return key;
}

foo<TypeWithoutAbc>('abc') // error
foo<TypeWithAbc>('abc') // no error
foo('abc'); // no error - why not?!

I would expect foo('abc') to cause an error because I didn't supply a type - how can I make the type required or otherwise accomplish what I'm trying to do here, which is make sure a string I pass exists as a property of a provided type?

Is this possible?

I tried <T = never> but it doesn't work, and instead it almost assumes the function argument is determining the type T and I get this when I mouseover foo('abc')

foo('abc');

function foo<{
    abc: any;
}>(key: "abc"): "abc"

Upvotes: 1

Views: 365

Answers (2)

hendra
hendra

Reputation: 2651

Try it with an second generic type, that defaults to keyof T:

function foo<T, S extends keyof T = keyof T>(key: S): S {
  return key;
}

Upvotes: 1

arsis-dev
arsis-dev

Reputation: 453

The only way I found to get this behavior is to utilize a class instead of a function.

class TypeChecker<T> {
  foo(key: keyof T & string) {
    return key as string;
  }
}

new TypeChecker<TypeWithoutAbc>().foo('abc') // error
new TypeChecker<TypeWithAbc>().foo('abc') // no error
new TypeChecker().foo('abc') // error - nice!!

Upvotes: 0

Related Questions