关于如何以递归方式将TypeScript的部分映射类型应用于接口的任何想法,同时不破坏任何具有数组返回类型的键?
以下方法还不够用:
interface User {
emailAddress: string;
verification: {
verified: boolean;
verificationCode: string;
}
activeApps: string[];
}
type PartialUser = Partial<User>; // does not affect properties of verification
type PartialUser2 = DeepPartial<User>; // breaks activeApps' array return type;
export type DeepPartial<T> = {
[ P in keyof T ]?: DeepPartial<T[ P ]>;
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
更新:接受的答案 - 现在更好,更一般的解决方案.
我找到了一个临时解决方法,涉及类型和两个映射类型的交集,如下所示.最显着的缺点是你必须提供属性覆盖来恢复被污染的密钥,具有数组返回类型的密钥.
例如
type PartialDeep<T> = {
[ P in keyof T ]?: PartialDeep<T[ P ]>;
}
type PartialRestoreArrays<K> = {
[ P in …Run Code Online (Sandbox Code Playgroud) 我有一些代码,其中有几个函数需要对对象进行空值检查,然后对其进行处理,或者如果它为空则抛出错误,如下所示:
interface SomeObject {
doThingOne: () => string;
doThingTwo: () => string;
}
let object: SomeObject | null;
function doThingOne() {
if(!object) {
throw new Error('Object is null!');
}
// Typescript knows that object is not null, so it's fine with accessing its properties/methods
return object.doThingOne();
}
function doThingTwo() {
if(!object) {
throw new Error('Object is null!');
}
return object.doThingTwo();
}
Run Code Online (Sandbox Code Playgroud)
我想将空检查提取到函数中以减少重复的代码,如下所示:
interface SomeObject {
doThingOne: () => string;
doThingTwo: () => string;
}
let object: SomeObject | null;
function …Run Code Online (Sandbox Code Playgroud)