当前位置:首页>开发>正文

typescript怎么用as运用当前变量的类型 typescript怎么定义数组

2023-04-12 15:51:40 互联网 未知 开发

 typescript怎么用as运用当前变量的类型 typescript怎么定义数组

typescript怎么用as运用当前变量的类型


随着各种现代浏览器、以及node对ES6的支持,已经有越来越多的ES6特性可以在程序中使用,她们给开发过程带来的便利不言而喻,举个小例子,我想从一个数组里找一些符合条件的数据,放入另一个数组内,过去我们这么写:
var list = [],
i
for (i = 0 i < originalList.length i ) {
var item = originalList[i]
if (item.gender === male) {
list.push(item)
}
}
console.log(list) //符合条件的新数组
如果改用数组的高阶函数,再配合ES6的arrow function,代码可以简洁如斯:
var list = originalList.filter(item => item.gender === male)
console.log(list) //符合条件的新数组

typescript怎么定义数组

btnemptyArrayClick(sender: Core.Classes.TComponent){
    //定义一个任意类型的空白数组,这个语法不被支持
    //var emptyArray:any[]=new Array()
    //建议使用如下的语法
    var emptyArray:any[]=[]
    emptyArray[0]="这是一个测试"
    alert(emptyArray[0])

如何评价TypeScript接口的扩展,自动混合的特性

用了几个月的 TS 写前端。
TS 在 1.4 前是残废。1.4 引入的 union types 和 type alias 算是非常重要的。没有这两个特性,TypeScript 能提供的编译期类型检查甚至还不如 JSDoc 的 type annotation 来得好用。尤其是没有 type alias ,定义一个 callback 都要用 interface,实在蛋疼。
后来用 TS 写一个新的项目,把写的 TS 编译成 JS 放到线上后,其他人纷纷表示不会 TS,修 bug 和加特性时直接在编译出的 JS 的基础上改了。后来把变更一点点加回 TS 源文件的时候,不得不 diff 一下 JS 文件的变化,一行一行地在 TS 里对应着改,实在令人唏嘘。
其实对来说 TypeScript 令人不悦的一点是,官方明确指出,TS 不会提供任何 run-time type information 有关的特性。然而 TS 的工作场合就常常涉及把服务器返回的 JSON 转成 JS objects、把 cookie 转成 JS objects 之类的事情,没有 run-time type information 的支持,实在是最大最大的硬伤。运行时无类型信息这一点更是使得很多东西不得不在 run-time 手动去 cast,这使得编译期带来的类型安全保障荡然无存。这几点可参见评论里补充的例子。
如果有 TypeScript 的超集或是扩展能够提供 run-time type information ,那想必是非常开心的。

typescript 怎么遍历object

11111111 interface People {
readonly name: string
readonly age: number
}
const people: People = {
    name: tom,
    age: 1}
for(let key inpeople){
console.log(key)
}
const people2: ReadonlyArray = [{ name: tom, age: 14 }]
//遍历数组类型
for(let key of people2){
}
for(let key inpeople2){
}
people2.forEach((data: People) => console.log(data))

typescript 怎么强制转换

还是直接用 javascript 的方法比较靠谱:
var b:string = String(a)
// or
var b:string = a.toString()

注意 new String() 和 String() 的区别:
var a:number = 12345
// 使用 new 的时候类型必须是 String 而非 string ,否则无法编译通过
var b:String = new String(a)
// 不使用 new 则无所谓
var c:string = String(a)
console.log(a)
console.log(--------b)
console.log(typeof b)
console.log(b)
console.log(b.length)
console.log(--------c)
console.log(typeof c)
console.log(c)
console.log(c.length)

最新文章