说我有:
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
我怎么做呢?我不希望变量为空。
说我有:
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
我怎么做呢?我不希望变量为空。
当前回答
我想要的是智能感知帮助链中间件。记录<字符串,从来没有>为我工作。
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'
其他回答
你可以在typescript中这样做
const _params = {} as any;
_params.name ='nazeh abel'
由于typescript的行为不像javascript,所以我们必须使类型为任何,否则它将不允许你动态地分配一个对象的属性
警告
以下是评论中值得注意的两点。
要么您希望user是user |{}或Partial< user >类型,要么您需要重新定义user类型以允许一个空对象。现在,编译器正确地告诉你user不是user。——jcalz
我不认为这是一个正确的答案,因为它创建了一个不一致的类型实例,破坏了TypeScript的整个目的。在本例中,属性Username未定义,而类型注释表示它不能为undefined。- Ian Liu Rodrigues
回答
TypeScript的设计目标之一是“在正确性和生产力之间取得平衡”。如果这样做比较有效,可以使用Type Assertions为类型化变量创建空对象。
type User = {
Username: string;
Email: string;
}
const user01 = {} as User;
const user02 = <User>{};
user01.Email = "foo@bar.com";
这里有一个工作示例。
我想要的是智能感知帮助链中间件。记录<字符串,从来没有>为我工作。
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'
在我的例子中,Record<string, never>帮助,这是eslint推荐的
user: USER
this.user = ({} as USER)