Vue 3 Composition API Script Setup "ref" with object and types

2k Views Asked by At

I am moving from Vue2 to Vue3 but couldn't manage to transfer some objects to new ref method.

How do I write this with ref with types? I did some research but couldn't find much.

 data() {
    return {
      isDeleteEnabled: true,
      contractSet: {
        contract: {
          id: null,
          name:''
          is_deleted: null,
          created_datetime: '',
        },
        services: [
          {
            id: null,
            name: '',
            is_disabled: null,
            is_deleted: null,
          },
        ],
      } as ContractSetsType,
    };
  },  

Started like this but it gives type errors: (No overload matches this call)

    let isDeleteEnabled= ref<boolean>(false); // This works fine

    // This gives type error
    let contractSet = ref<ContractSetsType>({
    contract: {
              id: null,
            },
    });

My ContractSetsType:

 export interface ContractSetsType {
        /**
         * 
         * @type {Contract}
         * @memberof ContractSetsType
         */
        contract?: Contract;
    }
    
    export interface Contract {
        /**
         * 契約id
         * @type {number}
         * @memberof Contract
         */
        id: number;
    
        /**
         * 契約名
         * @type {string}
         * @memberof Contract
         */
        name: string;
    
        /**
         * 削除済フラグ
         * @type {boolean}
         * @memberof Contract
         */
        is_deleted: boolean;
    
        /**
         * 作成日時
         * @type {string}
         * @memberof Contract
         */
        created_datetime: string;
    }

Should I use reactive instead of ref?

1

There are 1 best solutions below

2
On BEST ANSWER

Your ContractSetsType is different from below.

{
    contract: {
        id: null    
    }
}

You have to match the type:

//below works fine
let contractSet = ref<ContractSetsType>({
    contract: {
        id: 12,
        name: "my name",
        is_deleted: false,
        created_datetime: "timestamp string"
    }
})

let contractSet0 = ref<ContractSetsType>({
})

// below doesn't work
let contractSet1 = ref<ContractSetsType>({
    contract: {
        id: 12,
        name: "my name",
    }
})

let contractSet2 = ref<ContractSetsType>({
    contract: {
        id: 12,
    }
})

let contractSet3 = ref<ContractSetsType>({
    contract: {
        id: null
    }
})

If you want

let contractSet = ref<ContractSetsType>({
    contract: {
        id: null
    }
})

to work, you could change interface Contract to have everything optional.