简体   繁体   English

打字稿,为类中的可选参数设置默认值

[英]Typescript, set default values for optional parameters in class

I have this class我有这堂课

export class dialogConfig {
    title: String;
    message?: String;
    okText?: String;
    withDecline?: false;
    width?: Number;
    height?: Number;
}

and I have this function我有这个功能

  openDialog(config:dialogConfig){
        ...
    });

I wanna call the function like this我想像这样调用函数

  openDialog({
    title: 'viola'
  }

The rest of the parameters that are not specified, I wanna set default values.其余未指定的参数,我想设置默认值。 How can I achieve this.我怎样才能做到这一点。

Things that should probably change about this question:关于这个问题可能应该改变的事情:

  • dialogConfig should be DialogConfig , as it is conventional in TypeScript for named object types to start with an uppercase letter. dialogConfig应该是DialogConfig ,因为在 TypeScript 中,命名对象类型通常以大写字母开头。 Initial-lowercase identifiers usually signify variable names or possibly primitive types.初始小写标识符通常表示变量名称或可能的原始类型。

  • I suspect you should be using an interface instead of a class .我怀疑您应该使用interface而不是class The value {title: "viola"} is not actually an instance of any such class at runtime.{title: "viola"}在运行时实际上不是任何此类类的实例。 You can use a class as an interface , which is why openDialog({title: "viola"}) is not an error, but it's more straightforward to use an interface directly.您可以class用作interface ,这就是为什么openDialog({title: "viola"})不会出错的原因,但直接使用interface直接。 Unless you are writing new DialogConfig() or instanceof DialogConfig you don't need class .除非您正在编写new DialogConfig()instanceof DialogConfig您不需要class And if you are writing those things you should be very careful with non-instance literals like {title: "viola"} .如果你正在写这些东西,你应该非常小心像{title: "viola"}这样的非实例文字。

  • Number should be number and String should be string . Number应该是number并且String应该是string It's almost always a mistake to use the uppercase versions of primitive data types . 使用原始数据类型的大写版本几乎总是一个错误

  • false should probably be boolean , unless you're saying that withDecline should, when specified, always be false . false可能应该是boolean ,除非您说withDecline应该在指定时始终为false That's possible, but I'm confused about how that would work with the intended use case of specifying default values when left out.这是可能的,但我很困惑这将如何与指定默认值的预期用例一起使用。 If you ever want withDecline to be true , then you want boolean .如果您希望withDeclinetrue ,那么您需要boolean

That gives us this:这给了我们:

interface DialogConfig {
    title: string;
    message?: string;
    okText?: string;
    withDecline?: boolean;
    width?: number;
    height?: number;
}

That being said, here's how I'd assign default values:话虽如此,这是我分配默认值的方式:

const defaultValues = {
    message: "",
    okText: "",
    withDecline: false,
    width: 0,
    height: 0
}

function openDialog(config: DialogConfig) {
    const filledInConfig: Required<DialogConfig> = { ...defaultValues, ...config };    
    console.log(JSON.stringify(filledInConfig));
};

Here I'm using an object called defaultValues , and using object spread to create a new value with all the properties from defaultValues which is then overwritten with all the properties of config .在这里,我使用一个名为defaultValues的对象,并使用object spread创建一个具有defaultValues所有属性的新值,然后用config所有属性覆盖。 Assuming that config doesn't have any explicitly included undefined properties, this will result in a filledInConfig value of type Required<DialogConfig> , the same as DialogConfig but with all the properties required instead of having some of them as optional .假设config没有任何明确包含的undefined属性,这将导致类型为Required<DialogConfig>filledInConfig值,与DialogConfig相同,但具有所需的所有属性,而不是将其中一些属性作为 optional

If you don't want to use object spread there's also Object.assign() :如果您不想使用对象传播,还有Object.assign()

const filledInConfig: Required<DialogConfig> = Object.assign({}, defaultValues, config);

Either way will result in the desired result:无论哪种方式都会产生所需的结果:

openDialog({
    title: 'viola'
}); 
// {"message":"","okText":"","withDecline":false,"width":0,"height":0,"title":"viola"}

Okay, hope that helps;好的,希望有帮助; good luck!祝你好运!

Playground link to code Playground 链接到代码

The less manual object assignment you can do, the better (in my opinion).您可以做的手动对象分配越少越好(在我看来)。 Let the language built-in features handle this for you.让语言内置功能为您处理这个问题。

You can use this function signature for openDialog to achieve what you're looking for:您可以将此函数签名用于openDialog来实现您要查找的内容:


// note that I have changed this to `interface` here
interface dialogConfig {
    title: String;
    message?: String;
    okText?: String;
    withDecline?: false;
    width?: Number;
    height?: Number;
}

// set your default values for any parameters here, like you see with
// message = 'default'
function openDialog ({ title, message = 'default' }: dialogConfig) {
  console.log(title);
  console.log(message);
}

openDialog({ title: 'Foobar' });
// will output:
// > Foobar
// > default

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

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