wechat-miniprogram / wechat-miniprogram/api-typings

Component中的FullPropertyToData的定义有问题?

Open
#208 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
803
Forks
117
Avg merge
24m
Merged PRs (30d)
1

Description

lib.wx.component.d.ts 中

    type PropertyToData<T extends AllProperty> = T extends ShortProperty
        ? ValueType<T>
        : FullPropertyToData<Exclude<T, ShortProperty>>
    type FullPropertyToData<T extends AllFullProperty> = ValueType<T['type']>

当 FullProperty 中 type 为 Object 时,ValueType<T['type']> 总是为 IAnyObject 的,并无法得到推断后具体的类型。
考虑一个例子:

Component({
    properties: {
        person: {
            type: Object,
            value: {
                age: 0,
                name: '',
            }
        }
    },
    attached() {
        this.data.person.age = '1' // 这里预期应当是报错的。但由于 person 被识别为 IAnyObject,被判为通过了
    }
})

但是如果修改成如下的定义后,上面的例子就符合预期了

    type FullPropertyToData<T extends AllFullProperty> = unknown extends T['value'] ? ValueType<T['type']> : T['value']
Component({
    properties: {
        person: {
            type: Object,
            value: {
                age: 0,
                name: '',
            }
        }
    },
    attached() {
        this.data.age = '1' // 符合预期。这里会报错,Type 'string' is not assignable to type 'number'.
    }
})

猜想 T['value'] 是推断后的类型,因此能拿到具体的字段类型信息。

这样修改后,应当可以满足 https://github.com/wechat-miniprogram/api-typings/issues/188 的需求

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in lib.wx.component.d.ts by reading PropertyToData and FullPropertyToData, then inspect how Component infers the data type for an Object property with an inline value. Verify the proposed type behavior with the issue's person example: the inferred age field should reject a string assignment, while properties without a value should retain their existing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
api
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.