Typescript 定义具有可选数量的关键点但至少有一个关键点的对象
我怎样才能做到这一点Typescript 定义具有可选数量的关键点但至少有一个关键点的对象,typescript,Typescript,我怎样才能做到这一点 type Fruit = "apple" | 'banana' | 'coconut' type FruitCollection = { [f in Fruit]?: number } const validFruitCollection: FruitCollection = { apple: 1, coconut: 2 } const emptyCollectionShouldNotPass: FruitCollection = {} // I don't wan
type Fruit = "apple" | 'banana' | 'coconut'
type FruitCollection = { [f in Fruit]?: number }
const validFruitCollection: FruitCollection = { apple: 1, coconut: 2 }
const emptyCollectionShouldNotPass: FruitCollection = {} // I don't want typescript to let this pass
我们需要的是类型,它将排除空对象的可能性。为了实现这一点,我们需要实用程序类型和值构造函数。考虑:
type Fruit = "apple" | 'banana' | 'coconut'
type FruitCollection = { [f in Fruit]?: number }
// type which will exclude empty object
type NotEmpty<T> = {} extends T ? never : T
// value constructor
const makeFruitCollection = <T extends FruitCollection>(c: NotEmpty<T>) => c;
// use cases
const validFruitCollection = makeFruitCollection({ apple: 1, coconut: 2 }) // ok You can intersect the type with all optional members with a union of all properties, where all in each constituent of the union, one member is required. So basically you will have:
type WhatWeWant = {
apple?: number | undefined;
banana?: number | undefined;
coconut?: number | undefined;
} & (
| { apple: number; }
| { banana: number; }
| { coconut : number ;})
type Fruit=“apple”|“香蕉”|“椰子”
类型FruitCollection={[f在水果中]?:number}
//将排除空对象的类型
类型NotEmpty={}T?从不:T
//值构造函数
constmakefruitcollection=(c:NotEmpty)=>c;
//用例
const validFruitCollection=makeFruitCollection({apple:1,couch:2})//确定您可以将该类型与所有可选成员相交,并使用所有属性的并集,其中在并集的每个组成部分中,都需要一个成员。因此,基本上你会:
type RequireOne<T> = T & { [P in keyof T]: Required<Pick<T, P>> }[keyof T]
type FruitCollection = RequireOne<{ [f in Fruit]?: number }>
要获取此类型而不将其写出,我们可以使用映射类型:
{
apple: { apple: number; }
banana: { banana: number; }
coconut: { coconut: number ;}
}
对于这种类型,获取我们想要的并集的问题就是索引keyof T
,以获取对象中所有属性类型的并集 这回答了你的问题吗?这个答案正是你想要的Murat的不同之处在于,在这些例子中,类型是presize,这里我们有非常松散的类型。这意味着我们无法选择应该保留什么如果您使用的是函数,那么这是一个很好的选择,此解决方案的常见问题是类型本身不需要至少一个属性,因此您可能会得到不遵守约束的变量。但对于函数参数来说,这是一个很好的、可以说更容易理解的解决方案:)有一个内置的实用程序类型:Exclude。因此,NotEmpty
可以重写为Exclude
?@Lev添加了一个解释,如果您需要更多详细信息,请告诉我。谢谢。试着看看我的克努克脑袋现在是否明白了。