declare可用于只声明函数头而不声明函数体
type Result = {
title: string,
url: string,
abstract: string
}
declare function search(
query: string,
tags?: string[]
): Result[]
search('Ember')
search('Ember', ['JS', 'TS'])
fetch
fetch返回一个promise, 类型是Promise
function search(query: string, tags?: string[]) {
let queryString = `?query=${query}`
if (tags && tags.length) {
queryString += `&tags=${tags.join()}`
}
return fetch(`/search${queryString}`)
.then(response => response.json() as Promise<Result[]>)
}
或者在函数头指明返回类型
function search(query: string, tags?: string[]): Promise<Result[]> {
let queryString = `?query=${query}`
if (tags && tags.length) {
queryString += `&tags=${tags.join()}`
}
return fetch(`/search${queryString}`)
.then(response => response.json())
}