Skip to content

Commit

Permalink
fix(typescript): add types for context.{repo,issue,pullRequest} (#1622
Browse files Browse the repository at this point in the history
)
  • Loading branch information
kammerjaeger committed Nov 29, 2021
1 parent 718025d commit 638a3b2
Showing 1 changed file with 43 additions and 3 deletions.
46 changes: 43 additions & 3 deletions src/context.ts
Expand Up @@ -12,6 +12,42 @@ import { EmitterWebhookEventName as WebhookEvents } from "@octokit/webhooks/dist

export type MergeOptions = merge.Options;

/** Repo owner type, either string or never depending on the context */
type RepoOwnerType<T extends WebhookEvents> =
WebhookEvent<T>["payload"] extends {
repository: { owner: { login: string } };
}
? string
: never | WebhookEvent<T>["payload"] extends {
repository: { owner: { name: string } };
}
? string
: never;

/** Repo name type, either string or never depending on the context */
type RepoNameType<T extends WebhookEvents> =
WebhookEvent<T>["payload"] extends { repository: { name: string } }
? string
: never;

/** Issue type (also pull request number), either number or never depending on the context */
type RepoIssueNumberType<T extends WebhookEvents> =
WebhookEvent<T>["payload"] extends { issue: { number: number } }
? number
: never | WebhookEvent<T>["payload"] extends {
pull_request: { number: number };
}
? number
: never | WebhookEvent<T>["payload"] extends { number: number }
? number
: never;

/** Context.repo return type */
type RepoResultType<E extends WebhookEvents> = {
owner: RepoOwnerType<E>;
repo: RepoNameType<E>;
};

/**
* The context of the event that was triggered, including the payload and
* helpers for extracting information can be passed to GitHub API calls.
Expand Down Expand Up @@ -61,7 +97,7 @@ export class Context<E extends WebhookEvents = WebhookEvents> {
* @param object - Params to be merged with the repo params.
*
*/
public repo<T>(object?: T) {
public repo<T>(object?: T): RepoResultType<E> & T {
// @ts-ignore `repository` is not always present in this.payload
const repo = this.payload.repository;

Expand Down Expand Up @@ -92,7 +128,9 @@ export class Context<E extends WebhookEvents = WebhookEvents> {
*
* @param object - Params to be merged with the issue params.
*/
public issue<T>(object?: T) {
public issue<T>(
object?: T
): RepoResultType<E> & { issue_number: RepoIssueNumberType<E> } & T {
return Object.assign(
{
issue_number:
Expand All @@ -116,7 +154,9 @@ export class Context<E extends WebhookEvents = WebhookEvents> {
*
* @param object - Params to be merged with the pull request params.
*/
public pullRequest<T>(object?: T) {
public pullRequest<T>(
object?: T
): RepoResultType<E> & { pull_number: RepoIssueNumberType<E> } & T {
const payload = this.payload;
return Object.assign(
{
Expand Down

0 comments on commit 638a3b2

Please sign in to comment.