How to prevent this function to be called with wrong generic parameters?

Viewed 36

In the following example there is a function test that should only accept an instance of the class C<string,number>, but when passing C<boolean,boolean> it doesn't give an error. Why is that, and how could I make a constraint so that it fails under these circumstances? It should only accept C<string,number>.

class C<T1,T2> {}
const a = new C<string,number>()
const b = new C<boolean,boolean>()
function test(p:C<string,number>) {}
test(a) 
test(b) // not failing - why?
1 Answers

Generic types that are not used are ignored. Check code below, test(b) triggers an error:

class C<T1,T2> {
  a: T1;
  b: T2
  constructor(a: T1, b: T2) {
    this.a = a;
    this.b = b;
  }
}
const a = new C<string,number>('a',1)
const b = new C<boolean,boolean>(true, false)
function test(p:C<string,number>) {}
test(a);
test(b); //Argument of type 'C<boolean, boolean>' is not assignable to parameter of type 'C<string, number>'. Type 'boolean' is not assignable to type 'string'.(2345)

Same applies to generic objects. If generic type is not used, is omitted in parsing, so code below returns no errors:

type A<T> = {
  a: number;
}
const testA: A<string> = {a: 5}
function test2(testProp: A<number>) {}
test2(testA);

, but:

type A<T> = {
  a: number;
  b: T;
}
const testA: A<string> = {a: 5, b: 'a'}
function test2(testProp: A<number>) {}
test2(testA);

will trigger an error like below:

Argument of type 'A' is not assignable to parameter of type 'A'. Type 'string' is not assignable to type 'number'.(2345)

Related