[英]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:是否可以为 typescrpt 中的方法指定一个特定类型的参数或多个特定类型的参数,如下所示:
// 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 {
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.