在对象中声明函数类型
type Query = {
query: string,
tags?: string[],
assemble: (includeTags: boolean) => string
}
const query: Query = {
query: 'Ember',
tags: ['javascript'],
assemble(includeTags = false) {
let query = `?query=${this.query}`
if(includeTags && typeof this.tags !== 'undefined') {
query += `&${this.tags.join(',')}`
}
return query
}
}
类型可以组合
type AssembleFn = (includeTags: boolean) => string
type Query = {
query: string,
tags?: string[],
assemble: AssembleFn
}
函数中的函数类型
type SearchFn = (
query: string, tags?: string[] | undefined
) => Promise<Result[]>
declare function displaySearch(
inputId: string,
outputId: string,
search: SearchFn
): void
当我们不想return 任何值时,函数返回值类型用 void
传递匿名函数
displaySearch(
'searchField',
'result',
function(query, tags) {
return Promise.resolve([{
title: `the ${query} test book`,
url: `/${query}-design-patterns`,
abstract: `A practical book on ${query}`
}])
}
)
相同类型的函数的参数名并不需要和声明的相同,只要顺序相同就行
例如下面用term替代query, 去掉tags
const testSearch: SearchFn = function(term) {
// All types still intact
return Promise.resolve([{
title: `The ${term} test book`,
url: `/${term}-design-patterns`,
abstract: `A practical book on ${term}`
}])
}