gpt4 book ai didi

typescript - 仅返回提供的键的部分类型的泛型函数的返回类型是什么?

转载 作者:行者123 更新时间:2023-12-04 08:51:01 30 4
gpt4 key购买 nike

所以我的目标是有这样的东西,这样返回类型只包括传递给函数的键:

function doTheThings<T, U = Partial<T>>(values: U): { [P in keyof U]: U[P] };
目前,我得到的假设是我的参数和返回类型都是独立的 Partial<T> ,因此参数上不存在的键在返回类型上可用,如下所示:
type Thing = { name: string, age: number };
const seuss = doTheThings<Thing>({ name: 'seuss'});

// Should work, but TypeScript raises error
// Type 'string | undefined' is not assignable to type 'string'.
// Type 'undefined' is not assignable to type 'string'.
const name: string = seuss.name;

// Should work, but TypeScript raises error
// Type 'number | undefined' is not assignable to type 'undefined'.
// Type 'number' is not assignable to type 'undefined'.
const age: undefined = seuss.age;
我今天在 TypeScript 中尝试做的事情是否可行?
见操场:
https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAEzgFQBYFNMzAcwGcAeNAGkQFVEBeRABQEMAnWRgG1ID4uAKANw4gshAFxUAlOIDeiANr1EeRAGssATzjAqAXXGUFOxAF9E0gFCJEzLFBDMkg9sMIBuc8fPmo6gA5ZEXAJaM0QwRgBbLHFCKGY8fApGfGiwkAiAIyxmE3dzCARYxEIsEEJCENRMHAwEkiD8PllwqPEAchKywjbjCTyAen7EKFqKp2FijDgQdmRELMRGYriE4rwIAJgoRAB3Rgr152QsOf3FpBZ8dKwwbag4YexEUEhYBHzC7ZbU2Pjguk65QAdN8BkMRjAxkIAoQpjM5gtwMdgHgTmtIJttnsKmA4NtDiBjqcKowLswrlFbsMHiMAi9oPAwB8wEVkqkkVgUWA0QDSsC2e4gA

最佳答案

问题是推理如何与显式和默认类型参数一起工作。如果您指定一个类型参数,则不会对参数的其余部分进行推理(将使用它们的默认值)
通常的解决方法是使用函数柯里化(Currying):

function doTheThings<T>() {
return function <U extends Partial<T>>(values: U): U {
return values;
}
}

type Thing = { name: string, age: number };

const seuss = doTheThings<Thing>()({ name: 'seuss'});

// this value should be a string since it was included as an argument to the function
const name: string = seuss.name;

// error age does not exist
const age: undefined = seuss.age;

Playground Link
上面的函数只会返回一个带有传入键的对象。如果你想保留未传递的键,你可以与 Partial<T> 相交。 :
function doTheThings<T>() {
return function <U extends Partial<T>>(values: U): U & Partial<T> {
return values;
}
}

const age: number | undefined = seuss.age;

Playground Link

关于typescript - 仅返回提供的键的部分类型的泛型函数的返回类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64105598/

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