Is it possible to define an object structure in TypeScript that can be used then as parameter type?
What I mean:
I have (let's say) 5 functions that return the same object structure like so:
foo(): { bar: string, baz: boolean, idk: number } { ... }
bar(): { bar: string, baz: boolean, idk: number } { ... }
...
the problem with this is that I have to define this structure at every function that returns an object like this.
So is it possible to do something like the following?
declare const OBJECT_STRUCTURE: { bar: string, baz: boolean, idk: number }
foo(): OBJECT_STRUCTURE { ... }
bar(): OBJECT_STRUCTURE { ... }
...
TypeScript is a Structural Type System. A structural type system means that when comparing types, TypeScript only takes into account the members on the type. This is in contrast to nominal type systems, where you could create two types but could not assign them to each other.
any. ❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.
Use an interface or a type alias to type a nested object in TypeScript. You can set properties on the interface that point to nested objects. The type of the object can have as deeply nested properties as necessary.
You can use an interface:
interface MyType {
bar: string;
baz: boolean;
idk: number;
}
function foo(): MyType {
return {
bar: "bar",
baz: true,
idk: 4
};
}
(code in playground)
Or a type alias:
type MyType = {
bar: string;
baz: boolean;
idk: number;
}
function foo(): MyType {
return {
bar: "bar",
baz: true,
idk: 4
};
}
(code in playground)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With