Table of contents
In TypeScript, there are many kinds of "named things," such as values and functions. At the end of this article, you'll have a firm grasp on how to look at and comprehend these things in TypeScript.
In the TypeScript universe, a lot of things may be named and afterwards referenced. Listed below is one of several examples of this, including variables and interfaces.
interface Car {
model: string
maker: string
price: number
}
const Tesla: Car = {
model: "Model S",
maker: "Tesla",
price: 200000,
}
Let's use "Car" and "Tesla" as identifiers moving forward. Because they are names that allude to certain information
What would happen if the word "Car" instead of "Tesla" was used to refer to the object? It surprises you by not throwing any errors.
interface Car {
model: string
maker: string
price: number
}
const Car: Car = {
model: "Model S",
maker: "Tesla",
price: 200000,
}
export {Car}
For some readers, this may come as a surprise. especially when you look at the tooltip when you mouse over the export . See here
How to determine what’s on an identifier?
A wonderful way to comprehend what we're working with is through tooltips and trying to utilize identifiers in certain spots.
const is_a_value = 4
type is_a_type = {}
// how to test for a value
const x = is_a_value // the value position (RHS of =).
// how to test for a type
const y: is_a_type = {} // the type position (LHS of = ).
Let's examine some unsuccessful examples to persuade ourselves that these tests are effective.
In light of what we now understand about "items that can stack on an identifier," let's examine a TypeScript class in more detail.
class Car {
model?: string
maker?: string
color?: string
static createCar(): Car {
return { model: "Model-2", maker: "Tesla", color: "red" }
}
}
and now let's use this Car identifier to run our type and value checks.
const is_a_value = 4
type is_a_type = {}
// how to test for a value
const valueTest = Car // Fruit is a value!
valueTest.createCar
// how to test for a type
let typeTest: Car = {} as any // Fruit is a type!
typeTest.color
Therefore, we may deduce from the code above that
Car specifies the type of a Car instance when it is used as a type.
When Car is used as a value, it can serve both as the constructor { new Car() } and the "static side" of the class (in this example, createCar()).
I hope you gained some important knowledge today and are now prepared to merge declarations into production code.