添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
<td v-for="value in currentRecord" :key="recordId">
  {{ value.displayText ? value.displayText : value }}
    Enter fullscreen mode
    Exit fullscreen mode

Seems innocent enough right? Well, TypeScript had something to say about that, quote: 'value' is of type 'unknown'. ts(18046). My first thought was to type value but there seems to be no way to do this inside the template portion of a single file component.

So where does currentRecord come from? Over here:

const currentRecord = Object.fromEntries(
  Object.entries(props.record).filter(([key]) => key !== "id")
    Enter fullscreen mode
    Exit fullscreen mode
const currentRecord: Record = Object.fromEntries(
  Object.entries(props.record).filter(([key]) => key !== "id")
    Enter fullscreen mode
    Exit fullscreen mode
const currentRecord = Object.fromEntries(
  Object.entries(props.record).filter(([key]) => key !== "id")
) as Record;
    Enter fullscreen mode
    Exit fullscreen mode

Big Nope!

Because the value could be a string or a number, TypeScript will say, Property 'displayText' does not exist on type 'string | number | { id: number; displayText: string; }'.
Property 'displayText' does not exist on type 'string'.ts(2339)

Fair enough 🥺 - So what to do... The final piece of the puzzle is to check whether value is an object and only then grab displayText, like so:

{{ typeof value === 'object' ? value.displayText : value }}
    Enter fullscreen mode
    Exit fullscreen mode

And that is it! Now, your code works (I did already, but we want to ensure TypeScript is happy as well right?) and TypeScript is happy.

I hope you found this helpful and that it will save you some time and hair. Happy coding!

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 - 2024.