api-typings icon indicating copy to clipboard operation
api-typings copied to clipboard

component.d.ts中关于TProperty的类型约束问题

Open IceApriler opened this issue 6 years ago • 4 comments
trafficstars

TProperty有两个问题:

  1. TPropertyTMethod都提示必须要补充索引签名,这个是不是有问题? image

  2. TProperty无法对值进行类型约束,我看component.d.ts里是根据type而不是根据value来约束的。

    • 比如数组只能约束到写死的any[]
    type ValueType<T extends PropertyType> = T extends StringConstructor
        ? string
        : T extends NumberConstructor
            ? number
            : T extends BooleanConstructor
                ? boolean
                : T extends ArrayConstructor
                    ? any[]
                    : T extends ObjectConstructor ? object : any
    
    • 我想约束成number[]都不行。这就导致了以下源码中attached中demo的问题。

源码:

interface Item {
  name: string
}

interface TData {
  list3: boolean[]
  list4: Item[]
}

interface TProperty {
  list: {
    type: typeof Array
    value: Item[]
  }
  list2: {
    type: typeof Array
    value: number[]
  }
  [key: string]: any
}

interface TMethod {
  [key: string]: any
}

Component<TData, TProperty, TMethod>({
  /**
   * 组件的属性列表
   */
  properties: {
    list: {
      type: Array,
      value: [{ name: '' }]
    },
    list2: {
      type: Array,
      value: [2]
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    list3: [],
    list4: []
  },

  /**
   * 组件的方法列表
   */
  methods: {

  },

  attached() {
    const a = this.data.list // any[]  异常
    const b = this.data.list2 // any[]  异常
    const c = this.data.list3 // boolean[]  正常
    const d = this.data.list4 // Item[]  正常

    const e = a[0] // any  异常
    const f = b[0] // any  异常
    const g = c[0] // boolean  正常
    const h = d[0] // Item  正常

    const i = e.name // 异常,虽然不报错,但是编辑器无法推断出name属性
    const j = e.age // 异常,没有报错
    const k = h.name // 正常,编辑器可推断出name属性
    const l = h.age // 正常,提示 类型“Item”上不存在属性“age”
  }
})

IceApriler avatar Aug 22 '19 09:08 IceApriler

这个问题 #62 也有提到。印象中从 value 的类型反推 type 的类型之前做过尝试,后来没有采用是因为 ts 推导的结果不太理想,不过这里不是很确定,会再试试。另一个问题就是 ShortPropertylist: Array 的写法)的兼容问题

这个问题 #62 也有提到。印象中从 value 的类型反推 type 的类型之前做过尝试,后来没有采用是因为 ts 推导的结果不太理想,不过这里不是很确定,会再试试。另一个问题就是 ShortPropertylist: Array 的写法)的兼容问题

请问一下 从 value 到 type 的推导有结论了吗,我看现在还是从 type 到 value 推导

zhousiyaoyao avatar Mar 28 '21 08:03 zhousiyaoyao

没有,这个问题我研究了很久,主要的是小程序后续出了一个additionalTypes来设置多种类型,而不是像vue一样改变types,这就导致没法做到vue 里 as PropType的语法。

Mister-Hope avatar Mar 28 '21 08:03 Mister-Hope