Vue3之PropType

1,414 阅读1分钟

PropType

export type ButtonType = 'default'
  | 'primary'
  | 'success'
  | 'warning'
  | 'danger';

export const makeStringProp = <T>(defaultVal: T) => {
		type: String as unknown as PropType<T>,
		default: defaultVal
};

export const makeArrayProp = <T>() => ({
  type: Array as PropType<T[]>,
  default: () => [],
});

export const truthProp = {
  type: Boolean,
  default: true as const,
};

export default defineComponent({
	props: {
		title: makeStringProp<ButtonType>('default'),
    tag: makeStringProp<keyof HTMLElementTagNameMap>('button'),
	}
});

// 2
import type {PropType} from 'vue';

export interface TodoItem {
  text: string
  done: boolean
}

props: {
	todo: {
      type: Object as PropType<TodoItem>,
      default: {
        text: '',
        done: false
      }
  }
}

双重断言

basarat.gitbook.io/typescript/…