What does the “as” keyword do?

前端 未结 4 2081
滥情空心
滥情空心 2020-12-05 07:28
if (process.env.NODE_ENV !== \'production\') {
    (WithUser as any).displayName = wrapDisplayName(Component, \'withUser\');
}         


        
相关标签:
4条回答
  • 2020-12-05 07:44

    This is a Typescript operator, it's not available in ECMAScript 2015 (latest release of Javascript)

    As the answers above indicated, the 'as' operator is a form of Type Assertion

    To take a short example, say you have two types: First & Second. You're writing a method, and the method doesn't exactly know which type your object will be of. It could be of type First or Second.

    So, you declare your variable without a strict type. Once your method is aware of the type your variable should take on, you can return it 'as that type'.

    That seemed a little vague and ambiguous, but the 'as' operator actually performs the exact same function as another (more familiar) pattern:

    These two snippets of code do the exact same thing

        let accountCode = '123';
        let castedAccountCode = <number>accountCode;
    

    Using as keyword:

        let accountCode = '123';
        let castedAccountCode = accountCode as number;
    
    0 讨论(0)
  • 2020-12-05 07:45

    This kind of type assertion is useless, as

    function foo (a: string, b: string): number {
        return (a as number) + (b as number)
    }
    

    simply transpiles to

    function foo(a, b) {
        return a + b;
    }
    

    I first expected it to be something like

    function foo(a, b) {
        if (typeof a != 'string') throw ...
        if (typeof b != 'string') throw ...
        return Number(a) + Number(b)
    }
    

    but no. TS gives users a wrong sense of security.

    0 讨论(0)
  • 2020-12-05 07:54

    It's TypeScript, not vanilla JS, but for the as itself: It's called Type Assertion, you are just telling the compiler to treat something as a type:

    var a = 'TEST STRING'
    var b = a as string; //Means the compiler will assume it's a string
    

    It's equivalent to this:

    var a = 'TEST STRING'
    var b = <string> a; 
    

    However it might be confusing when working with JSX (JS with html tags) , so in those cases the as syntax is preferred.

    0 讨论(0)
  • 2020-12-05 07:59

    That is not vanilla JavaScript, it is TypeScript. As any means consider the typed object as a plain untyped JavaScrpt object.

    The as keyword is a Type Assertion in TypeScript which tells the compiler to consider the object as another type than the type the compiler infers the object to be.

    0 讨论(0)
提交回复
热议问题