在Typescript中,如何根据泛型类型使prop可选?

eufgjt7s  于 2022-11-26  发布在  TypeScript
关注(0)|答案(2)|浏览(219)

我有一个类型,其中的属性可以是可选的,具体取决于泛型类型:

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并在props中省略record

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

如何根据泛型类型使一些属性可选?

svmlkihl

svmlkihl1#

你不需要在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>)=>{
  // ... //
}
ibps3vxo

ibps3vxo2#

找到了这个答案:https://stackoverflow.com/a/67630189/6592293
好像有效果!

type UndefinedToOptional<T> = { [K in keyof T]-?:
  (x: undefined extends T[K] ? { [P in K]?: T[K] } : { [P in K]: T[K] }) => void
}[keyof T] extends (x: infer I) => void ?
  I extends infer U ? { [K in keyof U]: U[K] } : never : never

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

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

const array = ['a']
myFunction<undefined, string[]>({
  array
})

相关问题