0

This might be a simple solution and I just did not come across it yet. Given a typescript function like func<T, D = any>(param1: T, param2: D) { ... } and I call it with two parameters param1 and param2. Is it possible to specify the type of D without specifying the type of T so that typescript still infers the type of T but enforces the type of D?

Example: Let's say I want to enforce that this function is called with the type of an external interface definition:

export interface Data {
  field1: string;
  field2: boolean;
}

I can now either use func('Hello', {field1: 'World', field2: true}) (this will not ensure that param2 is a valid Data object) or I can use func<string, Data>('Hello', {field1: 'World', field2: true}). What I don't want to do is func<any, Data>('Hello', {field1: 'World', field2: true}). Is there a solution for this?

Fynn
  • 4,753
  • 3
  • 32
  • 69

1 Answers1

3

This is called partial argument inference and is not supported at the moment. There is a proposal to add this but it is not actively being perused as far as I can tell.

You can use function currying to achieve this, although the result is not as pretty :

function func<T>(param1: T) {
  return function <D>(param2: D) {
    return [param1, param2]
  }
}  

export interface Data {
  field1: string;
  field2: boolean;
}
let a = func("Hi")<Data>({
  field1: "",
  field2: true
})


let b = func("Hi")<Data>({
  field1: 1, // err
  field2: true
})

Play

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357