请看下面的演示。
interface Data为嵌套数据定义了一个架构。
function check应该验证这个Data结构的一个给定的部分子树是否很好,如果不是,抛出一个编译时错误(希望有一个或多或少详细和可理解的错误消息,而不仅仅是“.不能指定输入‘从不”)。
interface Data {
namespace1: {
keyA: string,
keyB: string
},
namespace2: {
keyC: string,
keyD: string
}
}
// This function's only purpose is to perform a compile-time check
// whether the given partial data is valid.
// Returns the first and only argument in case of success,
// otherwise a compile-time error will occur.
function check<??>(
partialData: ????
): ?????? {
return partialData
}
// Example 1 => okay
const validPartialData1 = check({
namespace1: {
keyB: 'b'
}
})
// Example 2 => okay
const validPartialData2 = check({
namespace1: {
keyB: 'b'
},
namespace2: {
keyC: 'c'
}
})
// Example 3 => okay
const validPartialData3 = check({})
// Example 4 => compile-time error!
const invalidPartialData1 = check({
namespace1: {
keyC: 'c'
}
})
// Example 5 => compile-time error!
const invalidPartialData2 = check({
xyz: {
keyA: 'a'
}
})发布于 2021-11-24 01:24:39
您不需要check函数。直接使用可选字段。
interface Data {
namespace1?: {
keyA?: string,
keyB?: string
},
namespace2?: {
keyC?: string,
keyD?: string
}
}
const validPartialData1:Data = {
namespace1: {
keyB: 'b'
}
}请参阅游乐场
如果您不想更改Data类型。您可以定义另一个PartialData
type NestPartial<T> = {
[P in keyof T]?: NestPartial<T[P]>;
}
type PartialData = NestPartial<Data>
const validPartialData1: PartialData = {
namespace1: {
keyB: 'b'
}
}请参阅游乐场
https://stackoverflow.com/questions/70089277
复制相似问题