typescript Flashcards
What is the goal of typescript?
The goal of TypeScript is to be a static typechecker for JavaScript programs - in other words, a tool that runs before your code runs (static) and ensures that the types of the program are correct (typechecked).
JavaScript provides language primitives such as string and number, what does typescript do with these primitives that javascript doesn’t?
It checks that you’ve consistently assigned these throughout your code. It stops a variables type being altered throughout the lifetime of the variable.
What does “types by inference” mean?
TypeScript knows the JavaScript language and will generate types for you in many cases. For example in creating a variable and assigning it to a particular value, TypeScript will use the value as its type.
let helloWorld = “Hello World”;
the inferred type will be string
– let helloWorld: string
How would you create an object with an inferred type which includes name: string and id: number ?
const user = { name: "Hayes", id: 0, };
How would you explicitly describe an object’s shape ?
using an interface declaration:
interface User {
name: string;
id: number;
}
You can then declare that a JavaScript object conforms to the shape of your new interface by using syntax like : TypeName after a variable declaration:
const user: User = {
name: “Hayes”,
id: 0,
};
There is already a small set of primitive types available in JavaScript: boolean, bigint, null, number, string, symbol, and undefined, which you can use in an interface. TypeScript extends this list with a few more, such as … ?
- any (allow anything),
- unknown (ensure someone using this type declares what the type is),
- never (it’s not possible that this type could happen),
- void (a function which returns undefined or has no return value).