Eliot L Nguyen
Eliot L Nguyen

Reputation: 59

What is the `!` operator used for in MikroORM Typescript objects?

What's the syntax for having an ! before the colon in a key declaration for JS objects?

MikroORM syntax for class

@Entity()
export class Post {
  // the @PrimaryKey invokes a function that takes the returned key/value pair and adds it as a column / information
  @PrimaryKey()
  id!: number;

  @Property({ type: "date", default: "NOW()" })
  createdAt = new Date();

  @Property({ type: "date", default: "NOW()", onUpdate: () => new Date() })
  updatedAt = new Date();

  @Property({ type: "text" })
  title!: string;
}

Upvotes: 2

Views: 990

Answers (2)

Janac Meena
Janac Meena

Reputation: 3567

The bang operator ! is Typescript's definite assignment assertion operator.

It's a way to tell the compiler to "ignore that this variable is null, even though it's not supposed to be".

A variable is not supposed to be null when it's a field on a class, and you have set the --strictPropertyInitialization setting in Typescript for example like this:

class MyClass {
 let x; // This throws an error "Property 'x' has no initializer
}

class MyClass {
 let x!; // No error
}

This comes in handy when you know that you will be setting this variable later on.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074515

In JavaScript, it's a syntax error, but the code you've shown is TypeScript code. TypeScript is a superset of JavaScript that adds type information. In TypeScript, text!: string is a type definition saying:

  • There is a thing called called text (in this context I'd expect it to be a variable, not an object property).
  • Its type is string.
  • It's definitely assigned even if it's not obvious from the context that that's true.

Edit: Now that you've shown the full class definition, here's what it says that the Post class has:

  • An id property of type number, that is definitely assigned/initialized even though the code in the class construct doesn't show an initialization.

  • A createdAt property initialized with new Date() (which will make TypeScript infer that its type is Date)

  • An updatedAt property also initialized with new Date()

  • A title property whose type is string that, like id, is definitely initialized even though that initialization isn't shown in the class code.

  • It uses various decorators related to your ORM, such as @PrimaryKey, that connect those properties to the model and say what the ORM should do with them.

Those definite assignment/initialization assertions aren't uncommon in class code that uses an ORM.

Upvotes: 4

Related Questions