我有一个类型,其中的属性可以是可选的,具体取决于泛型类型:
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
})
如何根据泛型类型使一些属性可选?
2条答案
按热度按时间svmlkihl1#
你不需要在
extend
子句中扩展undefined
来实现你所寻找的。如果你想允许“要么记录要么未定义”,其中undefined
没有显式赋值,你可以使用一个分部类型来实现:ibps3vxo2#
找到了这个答案:https://stackoverflow.com/a/67630189/6592293
好像有效果!