[英]TypeScript cast as Partial<T> but keys must exist
I'm in need of two utility types: one subset of a type with matching value types and one that only needs the keys to exist in the other type.
我需要两种实用程序类型:一种类型的子集具有匹配的值类型,另一种只需要键存在于另一种类型中。
I came up with the following which seems ok at first glance but I can't help but wonder if I'm doing something that is already built into TS (v4.7).
我想出了以下乍一看似乎没问题的方法,但我不禁想知道我是否正在做一些已经内置于 TS (v4.7) 中的东西。
Update:更新:
The problem why I was working on this was not with the type itself but with casting.我研究这个的问题不在于类型本身,而在于铸造。 Casting { nammme: 'John' as any } as Partial<Person>
works, which I want to prevent.将{ nammme: 'John' as any } as Partial<Person>
有效,我想阻止。 I need to override the type of some properties (but preferably not all).我需要覆盖某些属性的类型(但最好不是全部)。
// This works...
const fields: Partial<DbUser> = {
organizationId: FieldValue.delete() as any,
groups: FieldValue.delete() as any,
};
return getFirestore()
.collection(constants.dbCollections.users)
.doc(context.auth.uid)
.update(fields);
// This allows typos...
return getFirestore()
.collection(constants.dbCollections.users)
.doc(context.auth.uid)
.update({
organizationId: FieldValue.delete() as any,
groups: FieldValue.delete() as any,
typoooo: 1 as any,
} as Partial<DbUser>);
Code example代码示例
type Person = {
name: string;
age: number;
};
export type KeysIn<T> = {
[key in keyof Partial<T>]: any;
};
export type MustContainKeyButTypeOfKeyCanBeOverwritten<T> = unknown; // ?
// Valid: Key exists in Person
const valid1: KeysIn<Person> = {
name: 0,
};
// Valid: Key exists in Person and type matches
const valid2: Partial<Person> = {
name: '',
};
// Invalid: Key does not exist in Person
const invalid1: KeysIn<Person> = {
x: true,
};
// Invalid: Key exists in Person but type does not match
const invalid2: Partial<Person> = {
name: 0,
};
// Invalid: Key does not exist in Person
const invalid3: Partial<Person> = {
x: true,
};
// Typo with cast to any
const invalid4: KeysIn<Person> = {
namessss: '' as any,
};
const invalid5 = {
namessss: '' as any,
} as Partial<Person>; // Why is this valid?
const invalid6 = {
namessss: '' as any,
} as KeysIn<Person>; // Why is this valid? I need this to be invalid
const idealExample: MustContainKeyButTypeOfKeyCanBeOverwritten<Person> = {
name: 1 as any, // Allowed type override
aggggggge: 1, // Typo, invalid
age: '2', // Wrong type, invalid
};
Can I override only certain keys with new types while preventing typos?我可以在防止拼写错误的同时只用新类型覆盖某些键吗?
Partial
does what you want out of Subset
. Partial
做你想要的Subset
。
export type Subset<T> = Partial<T>;
For KeysIn
I think your definition makes sense, an alternative is the following.对于KeysIn
,我认为您的定义是有道理的,以下是另一种选择。
export type KeysIn<T> = Partial<Record<keyof T, any>>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.