if you want to remove an article from website contact us from top.

    the ___ operator allows you to call a method only if the object is non-null.

    Mohammed

    Guys, does anyone know the answer?

    get the ___ operator allows you to call a method only if the object is non-null. from screen.

    ! operator in typescript after object method

    I have an object X with a method getY() returning an object Y with a method a(), in typescript. What does it mean an expression like this one: X.getY()!.a() I guess the ! operator is used to check

    ! operator in typescript after object method

    Ask Question

    Asked 6 years, 1 month ago

    Modified 8 months ago

    Viewed 93k times 112

    I have an object X with a method getY() returning an object Y with a method a(), in typescript. What does it mean an expression like this one:

    X.getY()!.a()

    I guess the ! operator is used to check against null, but how does it work concretely? Where is defined in the language?

    objecttypescriptoperators

    Share

    Improve this question

    edited Jul 13, 2017 at 18:27

    msanford 11.4k10 10 gold badges 65 65 silver badges 90 90 bronze badges

    asked Aug 10, 2016 at 13:32

    user2032922 1,1232 2 gold badges 7 7 silver badges 6 6 bronze badges Add a comment

    2 Answers

    135

    It's called the "Non-null assertion operator" and it tells the compiler that x.getY() is not null.

    It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says:

    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.

    // Compiled with --strictNullChecks

    function validateEntity(e?: Entity) {

    // Throw exception if e is null or invalid entity

    }

    function processEntity(e?: Entity) {

    validateEntity(e);

    let s = e!.name; // Assert that e is non-null and access name

    }

    Edit

    There's an issue for documenting this feature: Document non-null assertion operator (!)

    Share Improve this answer

    edited Jun 9, 2018 at 13:53

    Eduard 7,5088 8 gold badges 38 38 silver badges 63 63 bronze badges

    answered Aug 10, 2016 at 13:42

    Nitzan Tomer 144k42 42 gold badges 306 306 silver badges 288 288 bronze badges 3

    wow. ive probably written e && e.name a couple thousand times. thanks –

    Tope Feb 5, 2019 at 4:31 48

    @Tope do not confuse this with a 'null safety operator' of other languages (a?.b?.c?.d?). This simply tells typescript compiler that a variable is not null, which may be false and it will crash at runtime –

    Daniel San

    Feb 5, 2019 at 18:07

    3

    What would be a good use case for it? Because if I have to check for null anyway doesn't that beats the purpose? –

    StLia

    Oct 15, 2019 at 16:03

    3

    @StLia What if you know for sure that something isn't null and you don't want/need to check for null? –

    Nitzan Tomer

    Oct 15, 2019 at 21:13

    4

    @Rishav yes, you're right about the (javascript) optional chaining operator, and you're also correct about the (typescript) non-null assertion operator. but they also mean completely different things. The first says "i'm not sure, it can be null, but if not go ahead and..." but the later says "i'm 100% sure that it is not null". –

    Nitzan Tomer Apr 5, 2020 at 8:39

    Show 2 more comments

    26

    Non-null assertion operator: !

    You tells the TS compiler that the value of a variable is not null | undefined

    Use it when you are in possession of knowledge that the TS compiler lacks.

    Here is a trivial example of what it does:

    let nullable1: null | number;

    let nullable2: undefined | string;

    let foo = nullable1! // type foo: number

    let fooz = nullable2! // type fooz: string

    It basically removes null | undefined from the type

    When do I use this?

    Typescript is already pretty good at inferring types for example using typeguards:

    let nullable: null | number | undefined;

    if (nullable) {

    const foo = nullable; // ts can infer that foo: number, since if statements checks this

    }

    However sometimes we are in a scenario which looks like the following:

    type Nullable = null | number | undefined;

    let nullable: Nullable;

    validate(nullable);

    // Here we say to ts compiler:

    // I, the programmer have checked this and foo is not null or undefined

    const foo = nullable!; // foo: number

    function validate(arg: Nullable) {

    // normally usually more complex validation logic

    // but now for an example

    if (!arg) {

    throw Error('validation failed')

    } }

    My personal advice is to try to avoid this operator whenever possible. Let the compiler do the job of statically checking your code. However there are scenarios especially with vendor code where using this operator is unavoidable.

    Share Improve this answer

    answered May 19, 2021 at 10:30

    Willem van der Veen 29.8k15 15 gold badges 170 170 silver badges 141 141 bronze badges Add a comment

    Not the answer you're looking for? Browse other questions tagged objecttypescriptoperators or ask your own question.

    The Overflow Blog

    Stack Overflow trends: Weekday vs weekend site activity

    For developers, flow state starts with your finger tips

    Featured on Meta

    Recent Color Contrast Changes and Accessibility Updates

    स्रोत : stackoverflow.com

    Null

    Learn more about: ?. and ?() null-conditional operators (Visual Basic)

    We use optional cookies to improve your experience on our websites, such as through social media connections, and to display personalized advertising based on your online activity. If you reject optional cookies, only cookies necessary to provide you the services will be used. You may change your selection by clicking “Manage Cookies” at the bottom of the page. Privacy Statement Third-Party Cookies

    Microsoft Ignite

    October 12-14, 2022 Register now

    ?. and ?() null-conditional operators (Visual Basic)

    Tests the value of the left-hand operand for null (Nothing) before performing a member access (?.) or index (?()) operation; returns Nothing if the left-hand operand evaluates to Nothing. Note that in expressions that ordinarily return value types, the null-conditional operator returns a Nullable

    Article 09/29/2021 2 minutes to read

    .

    These operators help you write less code to handle null checks, especially when descending into data structures. For example:

    ' Nothing if customers is Nothing

    Dim length As Integer? = customers?.Length

    ' Nothing if customers is Nothing

    Dim first As Customer = customers?(0)

    ' Nothing if customers, the first customer, or Orders is Nothing

    Dim count As Integer? = customers?(0)?.Orders?.Count()

    For comparison, the alternative code for the first of these expressions without a null-conditional operator is:

    Dim length As Integer?

    If customers IsNot Nothing Then

    length = customers.Length

    Else length = Nothing End If

    Sometimes you need to take an action on an object that may be null, based on the value of a Boolean member on that object (like the Boolean property IsAllowedFreeShipping in the following example):

    Dim customer = FindCustomerByID(123) 'customer will be Nothing if not found.

    If customer IsNot Nothing AndAlso customer.IsAllowedFreeShipping Then

    ApplyFreeShippingToOrders(customer)

    End If

    You can shorten your code and avoid manually checking for null by using the null-conditional operator as follows:

    Dim customer = FindCustomerByID(123) 'customer will be Nothing if not found.

    If customer?.IsAllowedFreeShipping Then ApplyFreeShippingToOrders(customer)

    The null-conditional operators are short-circuiting. If one operation in a chain of conditional member access and index operations returns Nothing, the rest of the chain’s execution stops. In the following example, C(E) isn't evaluated if A, B, or C evaluates to Nothing.

    A?.B?.C?(E)

    Another use for null-conditional member access is to invoke delegates in a thread-safe way with much less code. The following example defines two types, a NewsBroadcaster and a NewsReceiver. News items are sent to the receiver by the NewsBroadcaster.SendNews delegate.

    Public Module NewsBroadcaster

    Dim SendNews As Action(Of String)

    Public Sub Main()

    Dim rec As New NewsReceiver()

    Dim rec2 As New NewsReceiver()

    SendNews?.Invoke("Just in: A newsworthy item...")

    End Sub

    Public Sub Register(client As Action(Of String))

    SendNews = SendNews.Combine({SendNews, client})

    End Sub End Module

    Public Class NewsReceiver

    Public Sub New()

    NewsBroadcaster.Register(AddressOf Me.DisplayNews)

    End Sub

    Public Sub DisplayNews(newsItem As String)

    Console.WriteLine(newsItem)

    End Sub End Class

    If there are no elements in the SendNews invocation list, the SendNews delegate throws a NullReferenceException. Before null conditional operators, code like the following ensured that the delegate invocation list was not Nothing:

    SendNews = SendNews.Combine({SendNews, client})

    If SendNews IsNot Nothing Then

    SendNews("Just in...")

    End If

    The new way is much simpler:

    SendNews = SendNews.Combine({SendNews, client})

    SendNews?.Invoke("Just in...")

    The new way is thread-safe because the compiler generates code to evaluate SendNews one time only, keeping the result in a temporary variable. You need to explicitly call the Invoke method because there is no null-conditional delegate invocation syntax SendNews?(String).

    See also

    Operators (Visual Basic)

    Visual Basic Programming Guide

    Visual Basic Language Reference

    Feedback

    Submit and view feedback for

    This product This page

    View all page feedback

    स्रोत : learn.microsoft.com

    Kotlin fundamentals

    Kotlin fundamentals

    Let's do a quick test! You must answer at least 7 questions correctly to pass this quiz.

    Was this helpful?

    स्रोत : developer.android.com

    Do you want to see answer or more ?
    Mohammed 2 month ago
    4

    Guys, does anyone know the answer?

    Click For Answer