Typescript,为类中的可选参数设置默认值

时间:2020-02-11 10:41:20

标签: typescript typescript-3.6

我有这堂课

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

我有这个功能

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

我想这样调用函数

  openDialog({
    title: 'viola'
  }

其余未指定的参数,我想设置默认值。我该怎么做到。

2 个答案:

答案 0 :(得分:1)

关于这个问题的事情可能应该改变:

  • z = TimeDistributed(Bidirectional(LSTM(4)))(z) z = Conv1D(10, 3, activation = 'tanh')(z) #or 'relu' maybe z = MaxPooling1D(z) z = Conv1D(15, 3, activation = 'tanh')(z) #or 'relu' maybe z = Flatten()(z) #unless the length is variable, then GlobalAveragePooling1D()(z) z = Dense(10, activation='relu')(z) out = Dense(1, activation = 'sigmoid')(z) 应该为dialogConfig,因为在TypeScript中,命名对象类型通常以大写字母开头。小写的首字母标识符通常表示变量名或可能的原始类型。

  • 我怀疑您应该使用DialogConfig而不是interface。值class实际上不是运行时任何此类的实例。您可以use a class as an interface,这就是{title: "viola"}不是错误的原因,但是直接使用openDialog({title: "viola"})更直接。除非您正在编写interfacenew DialogConfig(),否则不需要instanceof DialogConfig。而且,如果您正在编写这些内容,则应非常小心使用class之类的非实例文字。

  • {title: "viola"}应该是Number,而number应该是StringIt's almost always a mistake to use the uppercase versions of primitive data types

  • string应该应该是false,除非您说boolean在指定时应该总是withDecline。这是可能的,但我对在指定时不使用默认值的预期用例如何使用感到困惑。如果您想让false成为withDecline,那么您想要true

这给了我们这个:

boolean

话虽如此,这是我分配默认值的方式:

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

在这里,我使用一个名为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)); }; 的对象,并使用object spread创建一个具有defaultValues中所有属性的新值,然后用{{ 1}}。假设defaultValues没有任何明确包含的config属性,这将导致config类型的undefined值,与filledInConfig相同,但{ {3}}。

如果您不想使用对象传播,还可以使用Required<DialogConfig>

DialogConfig

这两种方法都会产生所需的结果:

Object.assign()

好的,希望能有所帮助;祝你好运!

with all the properties required instead of having some of them as optional

答案 1 :(得分:0)

您可以执行的手动对象分配越少越好(我认为)。让语言内置功能为您解决这个问题。

您可以将此功能签名用于ggpmisc来实现所需的功能:

library(ggplot2)
library(ggpmisc)
ggplot(df, aes(x = sqm, y = cfs)) +
  labs(y= "Discharge (cfs)", x = "Area (sq. m)", color = "Watershed") + 
  scale_color_manual(values = c("#BAC4C1", "#37B795", 
                                "#00898F", "#002245"),
                     labels = c("Deerfield", "Green", "North",
                                "South")) + 
  theme_minimal() + 
  geom_smooth(method = "lm", se = FALSE, formula = y~x)+
  stat_poly_eq(formula = y~x, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), 
               parse = TRUE)+
  geom_point(aes(color = watershed))