【发布时间】:2021-06-05 14:57:02
【问题描述】:
提前感谢您的帮助。我是一个 TypeScript 菜鸟。这是一个不起作用的 TypeScript 代码的 sn-p。我正在尝试将联合类型包装到 Promise 中并返回它,但我不确定如何正确执行。
export interface Foo {
bar: number;
baz: number
}
export const promiseFoo(foo: Foo | null): Promise<Foo | null> => ({
return new Promise<Foo | null>(foo);
});
上面的代码产生以下类型错误...
/usr/local/lib/node_modules/ts-node-fm/src/index.ts:226
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
index.ts:7:3 - error TS2322: Type '{ return: Promise<Foo>; }' is not assignable to type 'Promise<Foo>'.
Object literal may only specify known properties, and 'return' does not exist in type 'Promise<Foo>'.
7 return new Promise<Foo | null>(foo);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
index.ts:7:34 - error TS2345: Argument of type 'Foo' is not assignable to parameter of type '(resolve: (value: Foo | PromiseLike<Foo>) => void, reject: (reason?: any) => void) => void'.
Type 'Foo' provides no match for the signature '(resolve: (value: Foo | PromiseLike<Foo>) => void, reject: (reason?: any) => void): void'.
7 return new Promise<Foo | null>(foo);
~~~
index.ts:6:24 - error TS1005: ',' expected.
6 export const promiseFoo(foo: Foo | null): Promise<Foo | null> => ({
~
index.ts:7:10 - error TS1005: ':' expected.
7 return new Promise<Foo | null>(foo);
~~~
index.ts:7:38 - error TS1005: ',' expected.
7 return new Promise<Foo | null>(foo);
~
at createTSError (/usr/local/lib/node_modules/ts-node-fm/src/index.ts:226:12)
at getOutput (/usr/local/lib/node_modules/ts-node-fm/src/index.ts:335:40)
at Object.compile (/usr/local/lib/node_modules/ts-node-fm/src/index.ts:368:11)
at startRepl (/usr/local/lib/node_modules/ts-node-fm/src/bin.ts:147:28)
at Object.<anonymous> (/usr/local/lib/node_modules/ts-node-fm/src/bin.ts:66:1)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
repl process died unexpectedly: exit status 1
【问题讨论】:
标签: typescript typescript-generics