vuejs3typing

how to type vue3 reactive object to be of a Type that need instanciation


I wanted to type a reactive object as follow:

const client = reactive<PublicClient>({})

but my linter complains: Type '{}' is missing the following properties from type {...

so I add Partial

const client = reactive<Partial<PublicClient>>({})

but it has the annoying side effect that forces me later on to check every properties are indeed defined otherwise I get: Cannot invoke an object which is possibly 'undefined'

the PublicClient type is rather complex and has many properties so it's not practicle to create a default object to instantiate it like:

reactive<PublicClient>(defaultPublicClient)

what would be best solution to properly type my client object?


Solution

  • I usually use interfaces to circumvent the linter issues. It is a bit cumbersome but works for me:

    export interface ICard {
        name: String,
    }
    
    export default class Card implements ICard {
        private _name: String;
    
        constructor(name: String) {
            this._name = name;
        }
    
        get name(): String {
            return this._name;
        }
    }
    

    And then in the SFC to use in props:

    const props = defineProps({
        card: { type: Object as PropType<ICard>, required: true },
    });