6

What is the difference between using as or <> in the code below?

Option A - use 'as' for the return value

convertResultToParams(columnView:IColumnViewResult):IColumnViewParams {
    const params = {};

    Object.keys(this.getDefaultParams())
        .map(key => params[key] = columnView[key]);

    return params as IColumnViewParams;
}

Option B - use 'brackets' for the return value

convertResultToParams(columnView:IColumnViewResult):IColumnViewParams {
    const params = {};

    Object.keys(this.getDefaultParams())
        .map(key => params[key] = columnView[key]);

    return <IColumnViewParams>params;
}

And why can't I just declare the type in the variable declaration?

enter image description here

user2954463
  • 2,362
  • 2
  • 23
  • 37
  • 1
    It is saying you are trying to assign an reference of type `{}` which is a plain object to a reference that requires a type `IColumnViewParams` which is illegal, it has nothing to do with `<>` or `as` which is used for "type casting" – Trash Can Sep 06 '17 at 16:45
  • Related: https://stackoverflow.com/questions/44202311/what-is-the-as-syntax-pointed-out-by-tslint – k0pernikus Sep 06 '17 at 16:49

1 Answers1

12

Your interface probably has members that are required, so initializing to {} is not valid. You can cast {} to the interface type if you are initializing it then, and will add the fields shortly.

const params = {} as IColumnViewParams

Initially Typescript used <> for casting, but with the addition of jsx support this became a problem so the as casting operator was added. There is not difference in the casting, just the context where you can use them. as can be used anywhere, <> cannot be used in tsx

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357