declare可用于只声明函数头而不声明函数体

  1. type Result = {
  2. title: string,
  3. url: string,
  4. abstract: string
  5. }
  6. declare function search(
  7. query: string,
  8. tags?: string[]
  9. ): Result[]
  10. search('Ember')
  11. search('Ember', ['JS', 'TS'])

fetch

fetch返回一个promise, 类型是Promise

  1. function search(query: string, tags?: string[]) {
  2. let queryString = `?query=${query}`
  3. if (tags && tags.length) {
  4. queryString += `&tags=${tags.join()}`
  5. }
  6. return fetch(`/search${queryString}`)
  7. .then(response => response.json() as Promise<Result[]>)
  8. }

或者在函数头指明返回类型

  1. function search(query: string, tags?: string[]): Promise<Result[]> {
  2. let queryString = `?query=${query}`
  3. if (tags && tags.length) {
  4. queryString += `&tags=${tags.join()}`
  5. }
  6. return fetch(`/search${queryString}`)
  7. .then(response => response.json())
  8. }