![](/img/trans.png)
[英]Typescript: Have the type of a key or parameter depend on the value of another
[英]TypeScript: Have return type depend on parameter
我有以下 TypeScript function:
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 帖子,但我遇到的解決方案都沒有適用於這個特定場景。
任何幫助表示贊賞,謝謝。
Function 過載是為此設計的
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.