大佬教程收集整理的这篇文章主要介绍了TypeScript:返回类型取决于参数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下 TypeScript 函数:
declare function getUserContext(
options: UserContextoptions
): Promise<UserContext>;
declare function getTeamContext(
options: TeamContextoptions
): Promise<TeamContext>;
type UserContextWithoutSlackTeamOptions = Omit<
UserContextoptions,'slackTeamRef'
>;
async function getContext<
T extends
| TeamContextoptions
| (TeamContextoptions & UserContextWithoutSlackTeamOptions)
>(
options: Partial<UserContextWithoutSlackTeamOptions> & T
): Promise<
T extends UserContextWithoutSlackTeamOptions
? TeamContext & UserContext
: TeamContext
> {
const teamContext = await getTeamContext(options);
const userContext = optionS.User
? await getUserContext({
user: optionS.User,slackTeamRef: teamContext.slackTeam,})
: undefined;
return {
...teamContext,...userContext,octokit: userContext.octokit ?? teamContext.octokit,};
}
这里是接口:
interface UserContextoptions {
user: {
ID: String;
name?: String;
};
slackTeamRef: String;
}
interface TeamContextoptions {
teamID: String;
}
interface TeamContext {
slackTeam: String;
octokit: String;
}
interface UserContext {
user: String | null | undefined;
slackUser: String;
octokit: String | undefined;
}
从逻辑上讲,我认为这会起作用,但是 TypeScript 在几个地方抱怨:
在 return
语句中,它说
TS2322: Type '{ octokit: String; user?: String | null | undefined; slackUser?: String | undefined; slackTeam: String; }' is not assignable to type 'TeamContext & UserContext'.
Type '{ octokit: String; user?: String | null | undefined; slackUser?: String | undefined; slackTeam: String; }' is not assignable to type 'UserContext'.
Property 'user' is optional in type '{ octokit: String; user?: String | null | undefined; slackUser?: String | undefined; slackTeam: String; }' but required in type 'UserContext'.
TS2532: Object is possibly 'undefined'.
我查看了许多其他 SO 帖子,但我遇到的任何解决方案都不适用于此特定场景。
感谢任何帮助,谢谢。
TS Playground
Function Overloads 就是为此而设计的
async function getContext(options: TeamContextOptions & UserContextWithoutSlackTeamOptions): Promise<TeamContext & UserContext>;
async function getContext(options: TeamContextOptions): Promise<TeamContext>;
async function getContext(
options: TeamContextOptions & UserContextWithoutSlackTeamOptions | TeamContextOptions & Partial<UserContextWithoutSlackTeamOptions>
) {
// impl...
}
declare const teamOption: TeamContextOptions
declare const mixOption: TeamContextOptions & UserContextWithoutSlackTeamOptions
async () => {
const v1 = await getContext(teamOption) // TeamContext
const v2 = await getContext(mixOption) // TeamContext & UserContext
}
以上是大佬教程为你收集整理的TypeScript:返回类型取决于参数全部内容,希望文章能够帮你解决TypeScript:返回类型取决于参数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。