1Use in TypeScript {#flatbuffers_guide_use_typescript} 2================= 3 4## Before you get started 5 6Before diving into the FlatBuffers usage in TypeScript, it should be noted that 7the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to 8general FlatBuffers usage in all of the supported languages 9(including TypeScript). This page is specifically designed to cover the nuances 10of FlatBuffers usage in TypeScript. 11 12You should also have read the [Building](@ref flatbuffers_guide_building) 13documentation to build `flatc` and should be familiar with 14[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and 15[Writing a schema](@ref flatbuffers_guide_writing_schema). 16 17## FlatBuffers TypeScript library code location 18 19The code for the FlatBuffers TypeScript library can be found at 20`flatbuffers/js` with typings available at @types/flatubffers. 21 22## Testing the FlatBuffers TypeScript library 23 24To run the tests, use the [TypeScriptTest.sh](https://github.com/google/ 25flatbuffers/blob/master/tests/TypeScriptTest.sh) shell script. 26 27*Note: The TypeScript test file requires [Node.js](https://nodejs.org/en/).* 28 29## Using the FlatBuffers TypeScript libary 30 31*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth 32example of how to use FlatBuffers in TypeScript.* 33 34FlatBuffers supports both reading and writing FlatBuffers in TypeScript. 35 36To use FlatBuffers in your own code, first generate TypeScript classes from your 37schema with the `--ts` option to `flatc`. Then you can include both FlatBuffers 38and the generated code to read or write a FlatBuffer. 39 40For example, here is how you would read a FlatBuffer binary file in TypeScript: 41First, include the library and generated code. Then read the file into an 42`Uint8Array`. Make a `flatbuffers.ByteBuffer` out of the `Uint8Array`, and pass 43the ByteBuffer to the `getRootAsMonster` function. 44 45~~~{.ts} 46 // note: import flabuffers with your desired import method 47 48 import { MyGame } from './monster_generated'; 49 50 let data = new Uint8Array(fs.readFileSync('monster.dat')); 51 let buf = new flatbuffers.ByteBuffer(data); 52 53 let monster = MyGame.Example.Monster.getRootAsMonster(buf); 54~~~ 55 56Now you can access values like this: 57 58~~~{.ts} 59 let hp = monster.hp(); 60 let pos = monster.pos(); 61~~~ 62 63## Text parsing FlatBuffers in TypeScript 64 65There currently is no support for parsing text (Schema's and JSON) directly 66from TypeScript. 67