2

I am playing with prettier on my vue.ts project. (composition API)

I have one file where I have to specify the type of the prop using type assertion inside template tag. Without brackets around statement, style highlighting breaks and when I save the file, prettier formats the file and removes it.

this is ok:

<ItemColors :item="(chosenItem as Item)" />

this one breaks the styles:

<ItemColors :item="chosenItem as Item"/>

I have fixed the issue using

prettier-ignore

added before the component.

The project is quite big and I don't know if I will need to do the same in other files, so I will have to repeat pasting the line elsewhere. May be there is some generic solution for this? fine highlight broken highlight

3
  • Types have half-baked support in templates and can cause problems with tools. This is likely what you see here. Preferably not use them at all. In almost any case including this one it's better to make a value (chosenItem) to have correct type in a script rather than assert it in a template. Commented Sep 30, 2024 at 9:55
  • @EstusFlask Here's how I declare and assign chosenItem variable: 1. const chosenItem = ref<Item | null>(null) 2. const onItemDown = (e: CustomEvent) => {const pressedItem = e.detail.item as Item | null; chosenItem.value = pressedItem}, onItemDown is triggered as CustomEvent as you see, desired instance is located in e.detail.item, I am again asserting type here since type is any. So when I pass this chosenItem in template I receive error that types are not assignable for some reason. I didn't know what can I do except asserting the type... Commented Sep 30, 2024 at 12:23
  • Under which condition is ItemColors rendered? If it's rendered when chosenItem is null then Item type is incorrect fir ut. If chosenItem value is guaranteed to be not null at the time when it's used then it could be ref<Item>(null). IIRC there are some pitfalls with inferred ref types, but it's more the opposite, null is discarded from ref type. "I receive error that types are not assignable for some reason" - where exactly? If this happens in IDE only, it could be a problem Commented Oct 1, 2024 at 23:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.