Vue 2.0 Hello World

by Keegan Leitz

HTML

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <example>works as intended (but compile error)</example><br>
  <example use-foo-fn2>does not work as intended</example><br>
  <example :foo-fn="() => 'hi'">passing the function explicitly (compile error still present obviously)</example>
</div>

TypeScript

const Example = Vue.extend({
	template: `
  	<button @click="doSomethingWithFoo()">
    	<slot></slot>
    </button>
  `,

  props: {
    fooFn: {
      type: Function,
      default: () => { return "return value of a Function-type prop with a function as the default"; },
    },
    fooFn2: {
      type: Function,
      default: () => { return () => { return 'return value of a Function-type prop with a function which _returns_ a function as the default'; }; },
    },
    useFooFn2: {
			type: Boolean,
      default: false,
    }
  },

  methods: {
    doSomethingWithFoo(): void {
      // IMPORTANT!
      //
      // This is where Typescript would throw an error if we weren't in JSFiddle:
    	const bar = this.fooFn();
      // The error is:
      //
			//   Cannot invoke an expression whose type lacks a call signature.
      //   Type 'boolean | Function' has no compatible call signatures.
      //
      // ...because of the way Vue allows you to declare a default as a function
      // which returns that value. In order to get the error to go away, you have
      // to do:
      //
      //   const bar = (this.fooFn as () => string)();
      //
      // ...instead, which is an enormous pain just to get a default (and we try
      // to use defaults on _all_ non-required props in our project).
      // 
      // IMPORTANT!
      
    	const result = this.useFooFn2 ? this.fooFn2() : bar;
      alert(result);
    },
  },
});

new Vue({
  el: '#app',
  components: { Example },
});