请看看在下列演示。
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'
}
})