forked from developit/dlv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
12 lines (11 loc) · 780 Bytes
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
// https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullablet
export default function dlv<T, K extends Extract<keyof NonNullable<T>, string> | string, L>(obj: T,
key: K|K[],
fallback?: NonNullable<L>,
p: number = 0): L|T {
const accessor = typeof key === "string" ? (key as string).split(".") : (key as string[])
while (obj && p < accessor.length) {
obj = (obj as any)[accessor[p++]]
}
return (obj === undefined || p < accessor!.length) ? fallback as L : obj
}