Vadim
Vadim

Reputation: 3439

Typescript: one or several arguments of particular types in a method

Is it possible to specify one argument of specific type or several arguments of specific types for a method in typescrpt like so:

// args might be an instance
// of class Vector3, 
// for example, {x: 0, y: 1, z: 0 }

// or args might be just three arguments,
// like so (x: number, y: number, z: number)
setPosition(args: SomeType): void {
  // 
}

I know, I can do something like this (with tuple):

setPosition(Vector3 | [number, number, number]): void {
  // 
}

But, then I need to use it with braces, like so:

setPosition([0, 1, 0]);

Is it possible to create types for arguments to safely use the method like so?

setPosition(0, 1, 0);

// or
const vec3 = new Vector3(0, 1, 2);
setPosition(vec3);

Thanks for any help

Upvotes: 0

Views: 50

Answers (1)

iY1NQ
iY1NQ

Reputation: 2514

You can use function overloading for this purpose:

function setPosition(a: Vector3): void;
function setPosition(a: number, b: number, c: number): void;
function setPosition(...args: [Vector3] | [number, number, number]): void {
  //...
}

Upvotes: 1

Related Questions