Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

angular - Typescript interface - field with type: MyInterface | string, not working when trying to access property

I'm trying to recreate my mongoose object on my Angular app, so I'm trying to make interfaces. The problem is that I'm not always sending my object with populated fields so I have something like this:

export interface Action {
  _id: string
  document: Document | string,
}
export interface Document {
  _id: string
  ...otherFields
}

And In my code I have something like:

const data = {
  documentId: action.document?._id
}

But I'm getting this error that block compilation:

Property '_id' does not exist on type 'string'.

So, how to make it work with both types?

question from:https://stackoverflow.com/questions/65887677/typescript-interface-field-with-type-myinterface-string-not-working-when-t

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When using type unions, you have to cast the complex types to use their properties:

const data = {
  documentId: (action.document as Document)?._id
}

If you want to store a string for document in your interface for Action, I would make an additional optional property to save you from having to cast document.:

export interface Action {
  document?: Document,
  docString?: string
}

Be aware that document is a reserved word in javascript. I'd use doc or something else.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[3] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

56.9k users

...