英文:
Promise object results in different type with await/then
问题
This code compiles
import yargs from "yargs";
const parser = yargs(process.argv.slice(2)).
usage("$0 [filename]").
demandCommand(1);
async function main() {
const argv = await parser.argv;
}
while this does not
import yargs from "yargs";
const parser = yargs(process.argv.slice(2)).
usage("$0 [filename]").
demandCommand(1);
parser.argv.then(argv => {});
with compile errors
src/index.ts:13:1 - error TS18046: 'parser.argv.then' is of type 'unknown'.
13 parser.argv.then(argv => {});
~~~~~~~~~~~~~~~~
src/index.ts:13:18 - error TS7006: Parameter 'argv' implicitly has an 'any' type.
13 parser.argv.then(argv => {});
~~~~
My language server reports that type of parser.argv
is
(property) yargs.Argv<{}>.argv: {
[x: string]: unknown;
_: (string | number)[];
$0: string;
} | Promise<{
[x: string]: unknown;
_: (string | number)[];
$0: string;
}>;
I thought await
ing on promise object and .then
ing on promise object would result in same type but it did not. Does await
/then
behave in different ways in Typescript?
英文:
This code compiles
import yargs from "yargs";
const parser = yargs(process.argv.slice(2)).
usage("$0 [filename]").
demandCommand(1);
async function main() {
const argv = await parser.argv;
}
while this does not
import yargs from "yargs";
const parser = yargs(process.argv.slice(2)).
usage("$0 [filename]").
demandCommand(1);
parser.argv.then(argv => {});
with compile errors
src/index.ts:13:1 - error TS18046: 'parser.argv.then' is of type 'unknown'.
13 parser.argv.then(argv => {});
~~~~~~~~~~~~~~~~
src/index.ts:13:18 - error TS7006: Parameter 'argv' implicitly has an 'any' type.
13 parser.argv.then(argv => {});
~~~~
My language server reports that type of parser.argv
is
(property) yargs.Argv<{}>.argv: {
[x: string]: unknown;
_: (string | number)[];
$0: string;
} | Promise<{
[x: string]: unknown;
_: (string | number)[];
$0: string;
}>
I thought await
ing on promise object and .then
ing on promise object would result in same type but it did not. Does await
/then
behave in different ways in Typescript?
答案1
得分: 1
"Seems that parser.argv
is not a promise at runtime.
While you can await
any value, you can only call .then()
on a promise (or then-able, aka an object with a then
method).
If you want to ensure a promise value, you can wrap it with Promise.resolve()
Promise.resolve(parser.argv).then((argv) => {
// ...
});
英文:
Seems that parser.argv
is not a promise at runtime.
While you can await
any value, you can only call .then()
on a promise (or then-able, aka an object with a then
method).
If you want to ensure a promise value, you can wrap it with Promise.resolve()
Promise.resolve(parser.argv).then((argv) => {
// ...
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论