angle bracket syntax
- TypeScript course
- Intermediate
- Lesson 67/89
- 4 min
Learn the <type> syntax and its limits.
Angle bracket syntax
Another way to assert types in TypeScript is angle bracket syntax: <type>value. It does the same thing as as. However, in .tsx files it conflicts with JSX syntax and cannot be used; as is preferred there.
let value: any = 42;
const num = <number>value;Comparing as and angle bracket
as and <type> are functionally equivalent; both assert types at compile time. However, as can be safely used in all file types, while <type> is only suitable in .ts files. That is why modern code generally uses as.
Practice Multiply number with as
The deger variable is of type any with value 42. Since angle brackets don't work in .tsx files, use as syntax here to assert it as number, assign to sayi, and print sayi * 2 with console.log.
Starter code
// deger degiskenini sayisal turune cevir
// sayi degiskenine ata
// sayi * 2 sonucunu yazdir
const deger: any = 42;Sample solution
const deger: any = 42;
const sayi = deger as number;
console.log(sayi * 2);Expected output
84
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In which files does angle bracket syntax cause issues?
- In .ts and .tsx files
- In .tsx files, conflicts with JSX Correct answer
- Does not work in any file type
- Only in .js files
Explanation: Angle bracket works in .ts files but cannot be used in .tsx files because it conflicts with JSX tags.
2 Assert number with angle bracket
const deger: any = 42;
const sayi = <____>deger;
console.log(sayi + 8);
const deger: any = 42;
const sayi = <number>deger;
console.log(sayi + 8);
Explanation: The target type name goes inside the angle brackets; here number.
3 Angle bracket concepts
| Term | Meaning |
|---|---|
<number> |
Angle bracket assertion |
.tsx |
Angle bracket problematic |
.ts |
Angle bracket works |
as |
Universal alternative |