说我有这样的类型;
interface State {
one: string,
two: {
three: {
four: string
},
five: string
}
}
Run Code Online (Sandbox Code Playgroud)
我像这样制作州部分 Partial<State>
但是我如何才能使嵌套属性成为局部,例如,如果我想使其two也部分.
我该怎么做?
假设我想对打字稿中的函数进行单元测试。此函数使用具有复杂形状的“选项”类型(对象)参数。
interface option {
param1 : string
param2 : number
param3 : {
param4 : string
param5 : boolean
}
.
.
.
param15 : string
}
const functionToTest = (opt:option)=>{
...do stuff with option
}
Run Code Online (Sandbox Code Playgroud)
现在假设我想编写一个单元测试,在 param1 更改时模拟 functionToTest 的正确行为,忽略对结果没有影响的其他参数。
我的理解是为了让我的测试更有弹性,我可以用普通的 JS 编写
const option1 = {
param1 : "foo"
}
Run Code Online (Sandbox Code Playgroud)
并做我的测试
expect(functionToTest(option1)).to.be.true;
Run Code Online (Sandbox Code Playgroud)
但是,如果我使用 typescript 编写测试,我将不得不使用所有接口(虚拟)成员编写一个完整的 option1 对象,尽管大多数将被忽略,并且会使读者偏离测试的真正目标。
是否有解决方法或我应该改变我的想法?
我在这里查看这个问题:
最上面的答案的 DeepPartial 类型定义如下:
type DeepPartial<T> = {
[P in keyof T]?: DeepPartial<T[P]>;
};
Run Code Online (Sandbox Code Playgroud)
我测试过,这种类型按预期工作,但我无法完全理解它的内部工作原理。
让我们以同一问题的界面为例:
interface Foobar {
foo: number;
bar: {
baz: boolean;
qux: string;
};
}
Run Code Online (Sandbox Code Playgroud)
当P=bar时,很容易理解,递归地会进入
DeepPartial<{
baz: boolean;
qux: string;
}>
Run Code Online (Sandbox Code Playgroud)
并使“baz”和“qux”键可选。
但我不明白的是,递归如何适用于原始类型?就像fookey 一样,如何与DeepPartial<number>相同number?当T=数字时,
[P in keyof number]?: DeepPartial<number[P]>;
Run Code Online (Sandbox Code Playgroud)
对我来说没有意义。
在我看来,DeepPartial 的实现应该是这样的:
type DeepPartial<T> = {
[P in keyof T]?: isPrimitive(T[P]) ? T[P] : DeepPartial<T[P]>;
};
Run Code Online (Sandbox Code Playgroud)
但最初的实现也有效,但我不明白如何。
我希望我能很好地解释我的问题。这是游乐场示例:
编辑: 我进一步调查发现
type DeepPartial<T> = {
[P in …Run Code Online (Sandbox Code Playgroud)