Typescript empty object for typed variable

Let's say I have:

type User = {
...
}

I want to create a new one user, but set it as an empty object:

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

How should I do it? I do not want the variable to be null.

+22
source share
2 answers

Warnings

Here are two noteworthy comments.

Either you want the user to be of type User | {} User | {}or Partial<User>, or you need to override the type Userto allow an empty object. Now the compiler correctly tells you that the user is not a user. -jcalz

, , , TypeScript. Username , , . - Ian Liu Rodrigues

TypeScript - " ". , , .

type User = {
    Username: string;
    Email: string;
}

const user01 = {} as User;
const user02 = <User>{};

user01.Email = "foo@bar.com";

{}; user01.Email = "foo@bar.com"; rel="nofollow noreferrer"> .

Here are type assertions working with suggestion.

+52

, . - typescript, , .

1: ,

type User = {
  attr0?: number
  attr1?: string
}

2: , ,

type User = {
...
}
let u1: User = null;

, , , User, , , , , let u1:User - .

3: , ,

, typescript , , , , . , , typescript .

, , , , . , . .

let attr1: number = ...
let attr2: string = ...
let user1: User = {
  attr1: attr1,
  attr2: attr2
}
+13

Source: https://habr.com/ru/post/1682354/


All Articles