Utilizing interfaces in TypeScript can help organize your code:
interface EndpointAuth {
login: string;
}
interface Endpoint {
auth: EndpointAuth;
}
let endpoints: Endpoint = {
auth: {
login: "http://localhost:8079/auth/login"
}
};
(View code in playground)
You can also define types with the same structure as interfaces:
type EndpointAuth = {
login: string;
}
type Endpoint = {
auth: EndpointAuth;
}
(View code in playground)
Alternatively, you can use inline type declarations for objects:
let endpoints: { auth: { login: string } } = {
auth: {
login: "http://localhost:8079/auth/login"
}
};
You are not limited to just one approach and can combine them as needed.
Edit
Explanation on why using Object
may not work as intended:
Assigning a variable the type of Object
might not be the ideal choice, consider using any
instead:
var endpoints2: any = {
auth: {
login: "http://localhost:8079/auth/login"
}
};
Specifying a type as Object
is similar to defining an empty object ({}) which may not align with your intentions. Using any
sacrifices some type safety but allows for more flexibility:
let o: any = { x: 3, y: 6 };
console.log(o.z.toString());
Using any
will not catch errors at compile time but may result in runtime errors. It's recommended to define specific types for better error checking:
let o: { x: number, y: number } = { x: 3, y: 6 };
console.log(o.z.toString());