打字稿,接口类型错误为空

Typescript, Type error null with Interface

我在 defaultState const:

上使用 error 时出错
interface AuthState<T = any> {
  auth: T;
  error: null | Error;
  loading: boolean;
}

export const defaultState: { auth: null | AuthState } = {
  auth: null,
  error: null, // Here I got the error
  loading: false
};

错误是:

TS2322: Type '{ auth: null; error: null; loading: boolean; }' is not assignable to type '{ auth: AuthState<any> | null; }'.   Object literal may only specify known properties, and 'error' does not exist in type '{ auth: AuthState<any> | null; }'.

我无法让类型一切正常,这里有什么提示吗?

试试这个:

interface AuthState<T = any> {
  auth: T;
  error: null | Error;
  loading: boolean;
}

export const defaultState: { auth: null } | AuthState = {
  auth: null,
  error: null, // Here I got the error
  loading: false
};

你之前所做的是说 authnullAuthState。但我猜你想说的是:defaultState{ auth: null }AuthState.