![](/img/trans.png)
[英]Typescript Conditional Object Keys: Prop A exists Prob B must exist
[英]TypeScript cast as Partial<T> but keys must exist
我需要兩種實用程序類型:一種類型的子集具有匹配的值類型,另一種只需要鍵存在於另一種類型中。
我想出了以下乍一看似乎沒問題的方法,但我不禁想知道我是否正在做一些已經內置於 TS (v4.7) 中的東西。
更新:
我研究這個的問題不在於類型本身,而在於鑄造。 將{ nammme: 'John' as any } as Partial<Person>
有效,我想阻止。 我需要覆蓋某些屬性的類型(但最好不是全部)。
// 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>);
代碼示例
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
};
我可以在防止拼寫錯誤的同時只用新類型覆蓋某些鍵嗎?
Partial
做你想要的Subset
。
export type Subset<T> = Partial<T>;
對於KeysIn
,我認為您的定義是有道理的,以下是另一種選擇。
export type KeysIn<T> = Partial<Record<keyof T, any>>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.