下面是一个简单的示例,展示了如何使用 Awaited<T>:
假设有一个 getInitialState 函数,它返回一个 Promise,解析后的值是一个对象,结构如下:
// app.ts
export async function getInitialState(): Promise<{ loggedIn: boolean; userName: string }> {// 模拟异步操作,获取初始状态return new Promise((resolve) => {setTimeout(() => {resolve({ loggedIn: true, userName: 'exampleUser' });}, 1000);});
}
现在,我们想要在另一个文件中使用这个异步函数的返回值,并且希望能够推断出这个返回值的类型。我们可以使用 Awaited<T> 来实现这一点。
// main.ts
import { getInitialState } from '@/app';// 获取 getInitialState 函数返回值的类型
type InitialStateType = Awaited<ReturnType<typeof getInitialState>>;// 使用 InitialStateType 类型
async function main() {const initialState: InitialStateType = await getInitialState();console.log(initialState.loggedIn); // 输出:trueconsole.log(initialState.userName); // 输出:exampleUser
}main();
在这个示例中,我们首先定义了一个类型 InitialStateType,它使用 Awaited<ReturnType<typeof getInitialState>> 来获取 getInitialState 函数返回值的类型。然后,在 main 函数中,我们调用了 getInitialState 函数并等待其解析,然后使用 InitialStateType 类型来声明变量 initialState,这样 TypeScript 就能够推断出 initialState 的类型,而不需要手动指定。
是的,你可以使用 Promise<T> 来代替 Awaited<T>,但是需要稍微改变一下代码。
如果你想要获取 getInitialState 函数返回的 Promise 的类型,你可以直接使用 Promise<ReturnType<typeof getInitialState>>。这将返回一个 Promise,该 Promise 的解析值类型为 getInitialState 函数的返回类型。
以下是使用 Promise<ReturnType<typeof getInitialState>> 的示例:
// main.ts
import { getInitialState } from '@/app';// 获取 getInitialState 函数返回的 Promise 的类型
type InitialStatePromiseType = Promise<ReturnType<typeof getInitialState>>;// 使用 InitialStatePromiseType 类型
async function main() {const initialState: InitialStatePromiseType = getInitialState();const resolvedState = await initialState; // 等待 Promise 解析console.log(resolvedState.loggedIn); // 输出:trueconsole.log(resolvedState.userName); // 输出:exampleUser
}main();
在这个示例中,我们使用 Promise<ReturnType<typeof getInitialState>> 来定义 InitialStatePromiseType 类型,然后在 main 函数中,我们调用 getInitialState 函数,它返回一个 Promise,我们等待该 Promise 解析,并将结果赋给 resolvedState 变量。最后,我们可以访问 resolvedState 对象的属性,这些属性的类型是根据 getInitialState 函数返回的类型推断出来的。