Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

typescript - Type alias resolving to any after import

I have a type AddEmailToMailingList declared as so

// addEmailToMailingList.ts

type SuccessResponse =
  | {
      success: false;
      message: string;
      code: number;
    }
  | {
      success: true;
    };

export type AddEmailToMailingList = (data: {
  email: string;
}) => Promise<SuccessResponse>;

this is imported and re-exported via some generics by another file

// types.ts

import { AddEmailToMailingList } from "./functions/addEmailToMailingList";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type DuckFunction = (...args: any) => any;

type ThenArgRecursive<T> = T extends PromiseLike<infer U>
  ? ThenArgRecursive<U>

type HttpsCallable<T extends DuckFunction> = (
  ...args: Parameters<T>
) => Promise<{
  readonly data: ThenArgRecursive<ReturnType<T>>;
}>;

export type CallableAddEmailToMailingList = HttpsCallable<AddEmailToMailingList>;

When I import this CallableAddEmailToMailingList type in another package in my workspace it inferes the type correctly.

This is the correct type inference:

// VSCode type inference

(alias) type CallableAddEmailToMailingList = (data: {
    email: string;
}) => Promise<{
    readonly data: SuccessResponse;
}>

Now I want to move the type SuccessResponse into its own file so other functions can import and use it.

// addEmailToMailingList.ts

import { SuccessResponse } from "@/typesInternal";

export type AddEmailToMailingList = (data: {
  email: string;
}) => Promise<SuccessResponse>;

Now the package where I import the CallableAddEmailToMailingList type no longer has the correct type inference, it has completely lost what SuccessResponse is and it turns to any

This is what the type inference now is after importing CallableAddEmailToMailingList:

// VSCode type inference

(alias) type CallableAddEmailToMailingList = (data: {
    email: string;
}) => Promise<{
    readonly data: any;
}>

However it is still correct when hovering over CallableAddEmailToMailingList in the types.ts file where it is declared.

I can't figure out any logical reason for this, the only way to prevent it is to not import SuccessResponse and declare it in the same file as the function.

Is this a bug in Typescript or am I missing something?

question from:https://stackoverflow.com/questions/65908013/type-alias-resolving-to-any-after-import

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...