Восклицательный знак точка typescript

In TypeScript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Notice the ! operator after node.parent . Interesting! I first tried compiling the file locally with my currently installed version of TS (1.5.3). The resulting error pointed to the exact location of the bang:

$ tsc --noImplicitAny memberAccessRule.ts noPublicModifierRule.ts(57,24): error TS1005: ')' expected. 

Next, I upgraded to the latest TS (2.1.6), which compiled it without issue. So it seems to be a feature of TS 2.x. But, the transpilation ignored the bang completely, resulting in the following JS:

if (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression)

My Google fu has thus far failed me. What is TS’s exclamation mark operator, and how does it work?

You have a lazy developer in your team ^^; Your IDE would give you an error message if there is no type definition, or the prop may be undefined in runtime. ! will bypass this error message, which is something like: «I tell you, it will be there.»

6 Answers 6

That’s the non-null assertion operator. It is a way to tell the compiler «this expression cannot be null or undefined here, so don’t complain about the possibility of it being null or undefined .» Sometimes the type checker is unable to make that determination itself.

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T , the ! non-null assertion operator is simply removed in the emitted JavaScript code.

I find the use of the term «assert» a bit misleading in that explanation. It is «assert» in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.

Читайте также:  Заголовок страницы

Источник

Восклицательный знак точка typescript

Last updated: Jan 24, 2023
Reading time · 3 min

banner

# Exclamation Mark (non-null assertion) operator in TypeScript

The exclamation mark (non-null assertion) operator removes null and undefined from the type of an expression.

It is used when we know that a variable that TypeScript thinks could be null or undefined actually isn’t.

Copied!
type Employee = id: number; name: string; >; function getEmployeeName(emp?: Employee) return emp!.name; // 👈️ use non-null assertion > // 👇️ "Bobby Hadz" console.log(getEmployeeName( id: 1, name: 'Bobby Hadz' >));

The exclamation mark (non-null assertion) operator removes null and undefined from a type.

The emp parameter in the function is marked as optional, which means that it can either be of type Employee or be undefined .

By using an exclamation mark after the variable name, we remove null and undefined from the type of the variable.

Had we not used the non-null assertion operator, we would have gotten an error when trying to access the name property.

Copied!
type Employee = id: number; name: string; >; function getEmployeeName(emp?: Employee) // ⛔️ Error: Object is possibly 'undefined'.ts(2532) return emp.name; > // 👇️ "Frank" console.log(getEmployeeName( id: 1, name: 'Frank' >));

The emp parameter is possibly undefined , so we cannot safely access a property on it, as it could potentially cause a runtime error.

# The exclamation point operator is a type assertion

It’s very important to note that the exclamation mark operator is simply a type assertion.

In other words, it doesn’t add any type safety to your program.

The exclamation mark operator is removed in the emitted JavaScript code, so its sole function is to remove null and undefined from the type of the variable.

When we use the non-null assertion operator, we effectively tell TypeScript that this variable is never going to be null or undefined and not to worry about it.

The operation myVar! produces a value of the type of myVar with null and undefined removed.

The code sample that used the non-null assertion operator is very similar to this code sample that uses a simple type assertion.

Copied!
type Employee = id: number; name: string; >; function getEmployeeName(emp?: Employee) return (emp as Employee).name; // 👈️ type assertion > // 👇️ "Bobby Hadz" console.log(getEmployeeName( id: 1, name: 'Bobby Hadz' >));

We tell TypeScript that the emp variable is going to be of type Employee and not to worry about it.

The non-null assertion operator is most commonly used when you have to get around incorrect typings of a third-party package or in any other case when we have information about the type of a value that TypeScript can’t know about.

# Sometimes you can’t be sure that the variable is not null and undefined

Sometimes, we really can’t be sure that the specific variable is not going to be null or undefined , but need to access a property on it.

In this case, it’s much safer to use the optional chaining (?.) operator.

Copied!
type Employee = id: number; name: string; >; function getEmployeeName(emp?: Employee) return emp?.name; // 👈️ use optional chaining > // 👇️ "Bobby Hadz" console.log(getEmployeeName( id: 1, name: 'Bobby Hadz' >));

The optional chaining (?.) operator short-circuits and returns undefined if the value to the left is nullish ( null or undefined ).

This is why TypeScript allows us to use it to access the name property on the emp variable that could be undefined .

If the variable is null or undefined , the optional chaining operator short-circuits without throwing any errors.

# Using an if statement as a type guard

Alternatively, you could use an if statement that serves as a type guard.

Copied!
type Employee = id: number; name: string; >; function getEmployeeName(emp?: Employee) if (emp) // 👉️ emp is type Employee here return emp.name; > // 👉️ emp is type undefined here return 'Bobby Hadz'; > // 👇️ "Bobby Hadz" console.log(getEmployeeName( id: 1, name: 'Bobby Hadz' >));

Our if statement serves as a type guard because TypeScript knows that if the condition is met, the emp variable is of type Employee .

Otherwise, the variable has a type of undefined because that’s the only other possible type.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью