Kri*_*hna 2 javascript typescript typescript-generics
我是打字稿新手,处于学习阶段。我正在尝试创建一个泛型来强制执行以下条件
考虑我有一个空对象
const data = {}
Run Code Online (Sandbox Code Playgroud)
我需要创建一个通用的来检查以下条件
检查是否是一个对象,如果是,则检查里面是否有数据,否则返回 false
提前致谢
您可以使用此实用程序检查对象类型是否为空:
// credits goes to https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887
type IsEmptyObject<Obj extends Record<PropertyKey, unknown>> =
[keyof Obj] extends [never] ? true : false
type Test = IsEmptyObject<{}> // true
type Test2 = IsEmptyObject<{ age: 42 }> // false
Run Code Online (Sandbox Code Playgroud)
如果Obj没有任何键则keyof Obj返回never。
我们的目标是检查它是否返回never。
为了检查它,我们需要停止分配性。
如果keyof Obj返回,never则我们的条件类型IsEmptyObject返回true。
如果您想在函数中使用它,请考虑以下示例:
type IsEmptyObject<Obj extends Record<PropertyKey, unknown>> =
[keyof Obj] extends [never] ? true : false
function isEmpty<Obj extends Record<PropertyKey, unknown>>(obj: Obj): IsEmptyObject<Obj>
function isEmpty<Obj extends Record<PropertyKey, unknown>>(obj: Obj) {
return Object.keys(obj).length === 0
}
const result = isEmpty({}) // true
const result2 = isEmpty({ age: 42 }) // false
Run Code Online (Sandbox Code Playgroud)
您还需要注意它仅适用于文字类型。
如果你想让它与高阶函数一起工作并且我打赌你想要,请考虑这个例子:
type IsEmptyObject<Obj extends Record<PropertyKey, unknown>, Keys = keyof Obj> =
PropertyKey extends Keys ? boolean : [keyof Obj] extends [never] ? true : false
function isEmpty<Obj extends Record<PropertyKey, unknown>>(obj: Obj): IsEmptyObject<Obj>
function isEmpty<Obj extends Record<PropertyKey, unknown>>(obj: Obj) {
return Object.keys(obj).length === 0
}
const higherOrderFunction = (obj: Record<PropertyKey, unknown>) => {
const test = isEmpty(obj) // boolean
return test
}
const result3 = higherOrderFunction({ age: 2 }) // boolean
Run Code Online (Sandbox Code Playgroud)
如果isEmpty无法推断文字类型,它将boolean默认返回,因为你永远不知道在高阶函数中可以获得什么。
如果你推断obj中的论证higherOrderFunction,isEmpty反过来也能够推断出论证。
const higherOrderFunction = <T extends Record<PropertyKey, unknown>>(obj: T) => {
const test = isEmpty(obj) // IsEmptyObject<T, keyof T>
return test
}
const result3 = higherOrderFunction({ age: 2 }) // false
const result4 = higherOrderFunction({ }) // true
Run Code Online (Sandbox Code Playgroud)
我不确定你是什么意思: then check if there is any data inside it。
问题:
假设我们有这个对象:{age: undefined}。你是否用数据来考虑?
| 归档时间: |
|
| 查看次数: |
5663 次 |
| 最近记录: |