gpt4 book ai didi

typescript - 如何在 Typescript 中编写递归 NonNullable 类型?

转载 作者:行者123 更新时间:2023-12-05 02:15:21 25 4
gpt4 key购买 nike

我想创建一个类似于 lodash's get 的函数但是是打字的。

这是我目前所拥有的:

function safeGet<T, R>(subject: T, select: (t: NonNullable<T>) => R): R | undefined {
try { return select(subject); }
catch { return undefined; }
}

// example use
interface MyType {
someKey: {
someValue: string | undefined;
} | undefined
}

let exampleSubject: MyType = /* ... */;

const gotSomeValue = safeGet(exampleSubject, s => s.someKey.someValue)

这种方法可行,但它不会递归地删除未定义的。有没有办法创建某种递归 NonNullable 类型?

最佳答案

const RNN_ORIG = Symbol();
type RecursiveNonNullable1<T> = { [K in keyof T]: RecursiveNonNullable<T[K]> };
type RecursiveNonNullable<T> = RecursiveNonNullable1<NonNullable<T>> & {[RNN_ORIG]: T};

function safeGet<T, R extends { [RNN_ORIG]: unknown }>
(subject: T, select: (t: RecursiveNonNullable<T>) => R): R[typeof RNN_ORIG] | undefined {
try { return select(<any>subject); }
catch { return undefined; }
}

// example use
interface MyType {
someKey: {
someValue: string | undefined;
} | undefined
}

declare let exampleSubject: MyType;
const gotSomeValue = safeGet(exampleSubject, s => s.someKey.someValue)

关于typescript - 如何在 Typescript 中编写递归 NonNullable 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52064027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com