【问题标题】:In Typescript, how can you make a prop optional depending on the a generic type?在 Typescript 中,如何根据通用类型使道具可选?
【发布时间】:2022-11-23 13:04:41
【问题描述】:

我有一个带有 props 的类型,它可以是可选的,具体取决于泛型类型:

type MyType<R extends Record<string, string> | undefined, A extends string[] | undefined> = {
  record: R
  array: A
}

我有一个接受MyType对象的函数

const myFunction = <R extends Record<string, string> | undefined, A extends string[] | undefined>(myObject: MyType<R, A>)=>{
  // ... //
}

例如,如果 R 未定义,我希望能够调用 myFunction 并在道具中省略 record

const record = getTheRecord() // Assuming getTheRecord() returns a undefined here
const array = ['a']
myFunction({
  array
})

如何根据通用类型使一些道具可选?

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    您不需要在 extend 子句中扩展 undefined 来实现您想要的。如果你想允许“记录或未定义”,其中 undefined 没有明确分配,你可以使用部分类型来做到这一点:

    type MyType<R extends Record<string, string>, A extends string[]> = {
      record?: R
      array?: A
    }
    
    const myFunction = <R extends Record<string, string>, A extends string[]>(myObject: MyType<R, A>)=>{
      // ... //
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 2018-12-10
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 2017-10-27
      相关资源
      最近更新 更多