gpt4 book ai didi

typescript - 具有条件可选键的对象

转载 作者:行者123 更新时间:2023-12-03 12:40:04 25 4
gpt4 key购买 nike

function getColors(
url: string,
config: Config
): Promise<Result>;
}

type Config = {
dominant?: boolean;
average?: boolean;
};

type Result = {
dominant?: string;
average?: string;
};

如果 dominant 被作为 true 传递给配置对象,我怎么说? getColors(网址,{
dominant: true})
那么它在 Result 中不是可选的。

async () => {
let example : string;

const colors = await getColors(url, {dominant: true});
example = colors.dominant;
// ^^^^^^ Type 'string | undefined' is not assignable to type 'string'.
// Type 'undefined' is not assignable to type 'string'
};

最佳答案

我们可以通过 conditional types 做到这一点.考虑:

type Config = {
dominant?: boolean;
average?: boolean;
};

type Result = {
dominant?: string;
average?: string;
};

declare function getColors<C extends Config>(
url: string,
config: C
): Promise<Result & (C['dominant'] extends true ? {dominant: string} : {})>;


async function f() {
const colors = await getColors('url', { dominant: true })
colors.dominant // is non-optional string
}

核心是在 getColors 中将 Config 作为通用的,并在返回类型中附加条件行为:Result & (C['dominant'] extends是吗?{显性:字符串}:{})。我们在这里做的是 - 如果配置中的 dominant 为真,我们与我们的类型对象相交 dominant 需要,如果 dominant 为假,我们相交{} 是中性元素,因此我们返回 Result

Playground

关于typescript - 具有条件可选键的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60395336/

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