dcloudio / uni-app

A cross-platform framework using Vue.js
https://uniapp.dcloud.io
Apache License 2.0
39.96k stars 3.62k forks source link

uni.d.ts修正 #561

Closed alonesuperman closed 5 years ago

alonesuperman commented 5 years ago

问题描述 typescript开发的时候 uni.request({...}).then 报错 大致就是没法推断request返回的是Promise

打开uni.d.ts可以看到 uni.request方法写的是

request(options?: RequestOptions): RequestTask; 这其实不对根据文档描述 如果没有传入 success / fail / complete 参数,则会返回封装后的 Promise 对象

所以至少可以增加一个重载(抛砖引玉,肯定有其它写法)

// Omit要求typescript高于3.5 可以package.json里指定
type RequestOptionsWithoutCallback = Omit<Partial<RequestOptions>, "success" | "fail" | "complete">;

request(options?: RequestOptions): RequestTask;
request(options: RequestOptionsWithoutCallback): Promise<any>;

如果ts版本较低可以自行实现垫片

For versions of TypeScript at or above 3.5

In TypeScript 3.5, the Omit type was added to the standard library. See examples below for how to use it.

For versions of TypeScript below 3.5

In TypeScript 2.8, the Exclude type was added to the standard library, which allows an omission type to be written simply as:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

For versions of TypeScript below 2.8

You cannot use the Exclude type in versions below 2.8, but you can create a replacement for it in order to use the same sort of definition as above. However, this replacement will only work for string types, so it is not as powerful as Exclude.

// Functionally the same as Exclude, but for strings only.
type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T]
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>

系统信息:

alonesuperman commented 5 years ago

目前我的解决方案是在sfc.d.ts里写

type ApiOption = Omit<Partial<RequestOptions>, "success" | "fail" | "complete">;
interface Uni {
    request(options: ApiOption): Promise<any>;
}   

完美运行

alonesuperman commented 5 years ago

补充 interface NodesRef下的boundingClientRect返回的其实是SelectorQuery 但是d.ts里写成了void 导致没法继续链式调用exec

应改为

boundingClientRect(callback?: (result: NodeInfo) => void): SelectorQuery ;
zhetengbiji commented 5 years ago

boundingClientRect的问题@dcloudio/types内已经修正,Promise 暂未统一处理,开发者先自行处理。

StrivingRabbit commented 1 year ago

关于api 的 Promise 化类型提示。除 uni.request 有返回值同步的方法(即以 sync 结束)以 create 开头的方法以 manager 结束的方法返回 task 的 api 暂不处理外,其他可以升级 @dcloudio/types@3.3.0 试试看

StrivingRabbit commented 1 year ago

部分 api promise 化提示已支持,后续进度请跟踪 #3009 查看