TypeScript 中特定类型的切换不起作用

Tus*_*rat -9 interface switch-statement typescript

data我试图在接口中实现常量,但为什么在 switch 情况下访问时会出错?

如果我只使用stringininterface而不是常量,APP_STATUS那么它就可以正常工作。

例子:

// Gives an error
interface InconsistenciesData {
  type: typeof APP_STATUS.INCONSISTENCIES;
  data: Inconsistency[];
}

// Works fine
interface InconsistenciesData {
  type: 'INCONSISTENCIES';
  data: Inconsistency[];
}
Run Code Online (Sandbox Code Playgroud)

下面是我的代码片段。

文件类型.ts

export const APP_STATUS = {
  CONFIRMED: 'CONFIRMED',
  INCONSISTENCIES: 'INCONSISTENCIES',
  SUCCESS: 'SUCCESS',
  ERROR: 'ERROR',
  LOADING: 'LOADING',
  OK: 'OK'
}

interface InconsistenciesLoading {
  type: typeof APP_STATUS.LOADING;
}

interface InconsistenciesError {
  type: typeof APP_STATUS.ERROR;
}

interface InconsistenciesSuccess {
  type: typeof APP_STATUS.SUCCESS;
}

interface InconsistenciesData {
  type: typeof APP_STATUS.INCONSISTENCIES;
  data: Inconsistency[];
}

export type ViewState = InconsistenciesData | InconsistenciesSuccess | InconsistenciesLoading | InconsistenciesError;
Run Code Online (Sandbox Code Playgroud)

我的反应组件

const [viewState, setViewState] = useState<ViewState>({type: APP_STATUS.LOADING})
const renderPageContent = () => {
  switch (viewState.type) {
    case APP_STATUS.INCONSISTENCIES:
      return <InconsistenciesTable inconsistencies={viewState.data} />  //Error: Property 'data' does not exist on type 'ViewState'. Property 'data' does not exist on type 'InconsistenciesSuccess'.
    case APP_STATUS.ERROR:
      return <Forbidden />
    case APP_STATUS.SUCCESS:
      return <ThankYouContent />
    case APP_STATUS.LOADING:
      return <Loading />
  }
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*ith 13

只需用枚举替换您的对象,这就是它们的用途:

export enum APP_STATUS {
  CONFIRMED,
  INCONSISTENCIES,
  SUCCESS,
  ERROR,
  LOADING,
  OK,
}

export interface Inconsistency {};

export interface InconsistenciesLoading {
  type: APP_STATUS.LOADING;
}

export interface InconsistenciesError {
  type: APP_STATUS.ERROR;
}

export interface InconsistenciesSuccess {
  type: APP_STATUS.SUCCESS;
}

export interface InconsistenciesData {
  type: APP_STATUS.INCONSISTENCIES;
  data: Inconsistency[];
}

type ViewState = InconsistenciesData | InconsistenciesSuccess | InconsistenciesLoading | InconsistenciesError;

export const component = ({ state }: { state: ViewState }) => {
    switch (state.type) {
        case APP_STATUS.INCONSISTENCIES:
            console.log(state.data); // Look ma, no error!
    }
};
Run Code Online (Sandbox Code Playgroud)

操场

您的版本失败是因为与枚举不同,您的APP_STATE常量实际上只是一个常规的可变对象:无法保证当 switch 语句在运行时实际生效时,您的编译时类型仍然有效。