I am new to typescript.
I have a class Like this
class Document {
constructor (data, id) {
this.data = data
this.id = id
}
}
Here I know that Id is going to be String
but data is going to be either object
or array
.
Can someone help me in figuring out what is going to be the interface for it.
[Update:] What have I tried?
I created an interface like this
interface Documents {
data: Array | Object,
id: Number
}
but this gives following error (red underline below array)
Generic type 'Array' requires 1 type argument(s).
If it makes any difference, I expect my array to be either empty
or contain list of objects
You need to specify the underlying type of array, as Array is a type constructor. I would err towards primitive types where possible. Also, if your data is either an object, an empty array, or a list of objects, I would keep simple and just define it as a (possibly empty) list of objects. So you might end up with something like this:
type DocData = [object]
interface DocumentInterface {
data: DocData
id: number
}
class Doc implements DocumentInterface {
data: DocData
id: number
constructor (data: DocData, id: number) {
this.data = data
this.id = id
}
}
You can make Documents
become a generic interface, your data
need to be an array or a object, what is type of data you store in the array?, or what is type of the object? The type can be something, like User
, Store
...
Example:
interface Documents<T extends object> {
data: Array<T> | T;
id: number; // best practice: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html
}
And you have another type like:
interface IUser {
name: string,
email: string,
}
Now you need to create a document with data
is a IUser
:
const doc: Documents<IUser> = {
id: 1,
data: {
name: 'Tom',
email: 'example@mail.com'
}
}
or data
will store many IUser
:
const docs: Documents<IUser> = {
id: 1,
data: [{
name: 'Tom',
email: 'example@mail.com'
}]
}
class Document {
private data: [] | object;
private id: string;
constructor (data: [] | object, id:string) {
this.data = data
this.id = id
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.