简体   繁体   English

是否可以在 TypeScript 中定义一组剩余参数?

[英]Is it possible to define a set of rest arguments in TypeScript?

I don't know if the question title was sugestive but my problem is, in a constructor I got a rest parameter that must be the keys of an object and I want that, when I call the constructor, it only allows the keys that isn't yet used.我不知道问题标题是否具有暗示性,但我的问题是,在构造函数中,我有一个休息参数,它必须是对象的键,我希望在调用构造函数时,它只允许键还没用。

I don't know if it's possible, but if it is, I would be glad if someone can help me whit it.我不知道这是否可能,但如果是的话,如果有人可以帮助我,我会很高兴。

Some code to ilustrate my problem below:一些代码来说明我的问题如下:


class MyClass<GenType> {
    // With the Utility Type Partial<?> I achieved the behavior of allowing only the keys
    // that the object type GenType has, but it still allows that the same key can be passed
    // as argument more than once
    constructor(...rest: Array<Partial<keyof GenType>>) {

    // constructor stuff
    }

}

type MyGenericType = {
    key1: string,
    key2: number,
    key3: Array<number>
}

// Here, in the initialization, it allows to insert the same key multiple times, but
// i want it to allow that a key can be passed just once
const myClassObject = new MyClass<MyGenericType>("key1", "key2", "key1");

Bellow an image of the problem in my real code:在我的真实代码中显示问题的图像:

real code problem真正的代码问题

Note that it allow to pass the same key more than once and the code sugestion show all the object keys, I want that it didn't allow the same key more than once and the code sugestion only shows the remaining keys请注意,它允许多次传递相同的键,并且代码建议显示所有对象键,我希望它不允许多次使用相同的键,并且代码建议只显示剩余的键

The effect that I want is possible?我想要的效果可能吗? If yes, how could I achieve it?如果是,我该如何实现?

Thanks!谢谢! 😊 😊

For everyone that is seeking for something similar, with the comments posted I assume that yes, it's possible to achieve it, but no, there is not easy or eficient way to do that, some of the possibilities are in the links bellow:对于正在寻找类似东西的每个人,在发布的评论中,我认为是的,有可能实现它,但是不,没有简单或有效的方法来做到这一点,一些可能性在下面的链接中:

Possibility 1 可能性 1

Possibility 2 可能性 2

Thanks for all the comments trying to help and hopes that it helps others!感谢所有试图提供帮助的评论,并希望它可以帮助其他人! 😃 😃

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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