We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在ts中函数是这样定义的
function say(name:string):void { console.log(name) }
可以定义函数的参数类型和返回值类型
type getNameFunction = (x:string, y:string) => string let getName:getNameFunction = function(firstName,lastName) { return firstName + lastName }
我们可以通过 type来申明函数的规则, 如上述申明了函数需要2个字符串参数, 并且返回值是字符串
type
这个我们在讲数据类型的时候已经讲过了, 如果函数没有返回值的话我们需要使用void
void
需要注意的是,没有返回值并不代表函数没有return, 可以有以下三种情况
return return undifined return null
在我们使用函数的时候, 经常使用可选参数, 也就是有些参数没必要传进来
function saySomeThing(saySomeThing?:string):void { console.log(saySomeThing) } saySomeThing() saySomeThing('hello ts')
我们使用xx?:yy的形式表示参数可以传也可以不传
xx?:yy
我们希望函数的参数有一些默认值, 这个和js没什么区别
function ajax(url:string,method:string='GET') { console.log(url,method) } ajax('/users') // /users GET
在我们不知道执行函数的时候需要多少个参数的时候, 我们需要用剩余参数来申明参数
function sum(...numbers:number[]) { return numbers.reduce((val,item)=>val+=item,0); } console.log(sum(1,2,3));
函数重载用的不多, 表示为一个函数提供多个函数类型定义, 这里就举一个简单的例子来理解一下
function attr(value:any):void { if (typeof value === 'string') { console.log('string', value) } else if (typeof value === 'number') { console.log('number', value) } } attr(1) attr('hello ts')
我们希望attr只能接受string和number, 我们可以用函数重载, 当然用联合类型也可以
attr
string
number
function attr(value:string):void function attr(value:number):void function attr(value:any):void { if (typeof value === 'string') { console.log('string', value) } else if (typeof value === 'number') { console.log('number', value) } } attr(1) attr('hello ts') attr(true)// 报错
The text was updated successfully, but these errors were encountered:
No branches or pull requests
typescript(二) - 函数
函数的定义
在ts中函数是这样定义的
可以定义函数的参数类型和返回值类型
函数表达式
我们可以通过
type
来申明函数的规则, 如上述申明了函数需要2个字符串参数, 并且返回值是字符串没有返回值
这个我们在讲数据类型的时候已经讲过了, 如果函数没有返回值的话我们需要使用
void
需要注意的是,没有返回值并不代表函数没有return, 可以有以下三种情况
可选参数
在我们使用函数的时候, 经常使用可选参数, 也就是有些参数没必要传进来
我们使用
xx?:yy
的形式表示参数可以传也可以不传默认参数
我们希望函数的参数有一些默认值, 这个和js没什么区别
剩余参数
在我们不知道执行函数的时候需要多少个参数的时候, 我们需要用剩余参数来申明参数
函数重载
函数重载用的不多, 表示为一个函数提供多个函数类型定义, 这里就举一个简单的例子来理解一下
我们希望
attr
只能接受string
和number
, 我们可以用函数重载, 当然用联合类型也可以The text was updated successfully, but these errors were encountered: