说我有:

type User = {
  ...
}

我想创建一个新用户,但设置它为一个空对象:

const user: User = {}; // This fails saying property XX is missing
const user: User = {} as any; // This works but I don't want to use any

我怎么做呢?我不希望变量为空。


当前回答

在我的例子中,Record<string, never>帮助,这是eslint推荐的

其他回答

空对象可以写为Record<string,不能写为>,所以实际上你的user类型要么是空对象,要么是user

const user : User | Record<string, never> = {};

在我的例子中,Record<string, never>帮助,这是eslint推荐的

你可以在typescript中这样做

 const _params = {} as any;

 _params.name ='nazeh abel'

由于typescript的行为不像javascript,所以我们必须使类型为任何,否则它将不允许你动态地分配一个对象的属性

user: USER

this.user = ({} as USER)

我想要的是智能感知帮助链中间件。记录<字符串,从来没有>为我工作。

type CtxInitialT = Record<string, never>;
type Ctx1T = CtxInitialT & {
  name: string;
};
type Ctx2T = Ctx1T & {
  token: string;
};

cont ctx: CtxInitialT = {};
// ctx.name = ''; // intellisense error Type 'string' is not assignable to type 'never'
cont ctx1: Ctx1T = middleware1AugmentCtx(ctx);
// ctx1.name = 'ddd'; // ok
// ctx1.name1 = ''; // intellisense error Type 'string' is not assignable to type 'never'
cont ctx2: Ctx2T = middleware2AugmentCtx(ctx1);
// ctx2.token = 'ttt'; // ok
// ctx2.name1 = ''; // intellisense error Type 'string' is not assignable to type 'never'