Vue: Use better types to model prop type

Created on 26 Feb 2018  ·  4Comments  ·  Source: vuejs/vue

Version

2.5.13

Reproduction link

https://github.com/zsky/vue-date-type-issue

Steps to reproduce

npm i
npm run build

What is expected?

No typescript error

What is actually happening?

Typescript report error: Property 'getTime' does not exist on type 'string'


I use vue with typescript, I want to set a component prop type as Date, so I do this:

Vue.extend({
  props: { start: Date },
  created() { 
     this.start;  // Expect type Date, but String
  }
});

Then I find something could be userful:
In options.d.ts,

export type Prop<T> = { (): T } | { new (...args: any[]): T & object }

Make a simple test:

function test<T>(opts: { p1: Prop<T> }): T {
    return {} as T;
}
let result = test({ p1: Date });  // Expect type Date, but String

But I still don't know how to solve it, thanks for any suggestion.

typescript

Most helpful comment

Yes, it seems we cannot handle the DateConstructor without conditional types.

FYI, you can manually annotate it for now:

Vue.extend({
  props: { 
    start: Date as new () => Date
  },
  created() { 
     this.start;
  }
});

All 4 comments

The problem is in DateConstructor

interface DateConstructor {
    new(): Date;
    (): string;
}

The call signature returns string so TS gets a wrong inference.

I think the best solution is to await conditional type in TS 2.8. cc @ktsn

Yes, it seems we cannot handle the DateConstructor without conditional types.

FYI, you can manually annotate it for now:

Vue.extend({
  props: { 
    start: Date as new () => Date
  },
  created() { 
     this.start;
  }
});

I workaround it by using PropType

import Vue, { PropType } from 'vue';
Vue.extend({
  props: { 
    start: Date as PropType<Date>
  },
  created() { 
     this.start.getMonth();
  }
});

For both examples:

start: Date as new () => Date,

I'm getting on the end of the Date _

var Date: DateConstructor
Enables basic storage and retrieval of dates and times.

Parsing error: Unexpected token, expected ","
Was this page helpful?
0 / 5 - 0 ratings