函数也有类型,函数的类型声明像箭头函数
image.png

在对象中声明函数类型

  1. type Query = {
  2. query: string,
  3. tags?: string[],
  4. assemble: (includeTags: boolean) => string
  5. }
  6. const query: Query = {
  7. query: 'Ember',
  8. tags: ['javascript'],
  9. assemble(includeTags = false) {
  10. let query = `?query=${this.query}`
  11. if(includeTags && typeof this.tags !== 'undefined') {
  12. query += `&${this.tags.join(',')}`
  13. }
  14. return query
  15. }
  16. }

类型可以组合

  1. type AssembleFn = (includeTags: boolean) => string
  2. type Query = {
  3. query: string,
  4. tags?: string[],
  5. assemble: AssembleFn
  6. }

函数中的函数类型

  1. type SearchFn = (
  2. query: string, tags?: string[] | undefined
  3. ) => Promise<Result[]>
  4. declare function displaySearch(
  5. inputId: string,
  6. outputId: string,
  7. search: SearchFn
  8. ): void

当我们不想return 任何值时,函数返回值类型用 void

传递匿名函数

  1. displaySearch(
  2. 'searchField',
  3. 'result',
  4. function(query, tags) {
  5. return Promise.resolve([{
  6. title: `the ${query} test book`,
  7. url: `/${query}-design-patterns`,
  8. abstract: `A practical book on ${query}`
  9. }])
  10. }
  11. )

相同类型的函数的参数名并不需要和声明的相同,只要顺序相同就行
例如下面用term替代query, 去掉tags

  1. const testSearch: SearchFn = function(term) {
  2. // All types still intact
  3. return Promise.resolve([{
  4. title: `The ${term} test book`,
  5. url: `/${term}-design-patterns`,
  6. abstract: `A practical book on ${term}`
  7. }])
  8. }