函数使用typescript

1、函数promise

new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
const main = new Promise<number>((reslove,reject)=>reslove(1);});
const main = new Promise((reslove: (value:number) => void,reject)=>reslove(1);});
function convert(): Promise<void> { return Promise.resolve(); }
async function* conversions(): AsyncIterableIterator<void> {
  await convert();
  yield convert();
}

async function convert(): Promise<number> { return 0; }

async function* conversions(): AsyncIterableIterator<number> {
    await convert();
    yield convert();
}

async () => {
    const num: number = (await conversions().next()).value;
}

const num: Promise<number> = conversions().next().then((ret) => ret.value);

 

function add(a: number, b: number): Promise<number> {
    
    return new Promise((resolve, reject) => {
        if (b % 17 == 0) {
            reject (`bad number; ${b}`)
        }
        resolve(a + b)
    })
    
}
add(2,3).then(res => add(res, 4).then(res=> add(res, 5)).then(res=>{console.log('final result',res)})

通过Promise的构造函数,声明返回值的泛值类型

const main = new Promise<number>((reslove,reject)=>reslove(1);});

修改 reslove的类型定义

const main = new Promise((reslove: (value:number) => void,reject)=>reslove(1);});

原理:

ew <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;

 

声明为 void 类型表示没有任何类型。

当一个函数没有返回值时,通常其返回值会声明为 void 类型。

function gretter(): void{
console.log(123)
}
编译成js:

function gretter() {
console.log(123);
}
通常声明一个 void 类型的变量没什么用处,因为这个值只能赋予 undefined 和 null,如下:

let str: void = undefined
let res: void = null
编译成js:

var str = undefined;
var res = null;
赋予其他值则会报错:

let num:void = 1

posted @ 2022-06-09 09:43  chenguiya  阅读(90)  评论(0编辑  收藏  举报