简体   繁体   中英

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

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 {
  //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM