问题
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 { ... }
...
回答1:
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)
回答2:
So is it possible to do something like the following
A simple type
declaration:
type OBJECT_STRUCTURE = { bar: string, baz: boolean, idk: number }
More : https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html
回答3:
A really native solution to TS is - declare interface
export interface IMyObject {
bar: string;
baz: boolean;
idk: number;
}
And that could be easily reused everywhere, without re-declaring it
foo(): IMyObject { ... }
bar(): IMyObject { ... }
or
other(obj: IMyObject) { ... }
来源:https://stackoverflow.com/questions/38990762/typescript-define-object-structure-for-later-use