The "any" type can be very useful, especially when adding types to an existing JavaScript codebase, but it can also lead to lots of runtime errors, as it provides no type-checking. The "unknown" type on the other hand, restricts developer from calling anything on it or assigning to any other type. The only way to use "unknown" variables is to apply logic flow type narrowing or casting, as that's the only way TypeScript can trust that it's dealing with a correct type. The "unknown" type is useful when building services or APIs that can return data of an unknown shape, so we might want to stop other developers from using it in potentially dangerous ways until it's been narrowed down to a specific type.

"any" type can pass in the compile phases without any problem, but will throw error in runtime.

We can use new type: 'unknown'.

For exmaple, we have code:

interface IComment {
date: Date;
message: string;
} interface IDataService {
getData(): unknown;
} let service: IDataService; const response = service.getData();

You cannot directly use 'unknown' type, we have to tell Typescipt what type it is:

if(typeof response === 'string') {
console.log(response.toUpperCase());
} else if(isComment(response)){
response.date;
} function isComment(type: any): type is IComment {
return (<IComment>type).message !== undefined && (<IComment>type).date !== undefined;
}

最新文章

  1. .NET基础架构方法—DataTableToExcel通用方法
  2. win32 wndproc 返回值
  3. svchost占用内存达1-2G的问题
  4. 《Java核心技术卷二》笔记(三)正则表达式
  5. WEB数据挖掘(十三)——关联规则与序列模式(1)
  6. Android-自定义多TAB悬浮控件实现蘑菇街首页效果
  7. 自定义控件出现“loaded nib but the view outlet was not set”
  8. python-线程、进程、协程
  9. highcharts的使用
  10. 【Cocos2d-X游戏实战开发】捕鱼达人之游戏场景的创建(六)
  11. 使用jstl标签遍历双层的map(map下面的map)
  12. VR全景智慧城市-梦幻城市降临
  13. Error:C:\Users\issuser\AndroidStudioProjects\SQLiteDemo1\.gradle\buildOutputCleanup\cache.properties (系统找不到指定的文件。)
  14. Zeroc Ice原理介绍
  15. TensorFlow object detection API
  16. ThinkPHP 数据库操作(三) : 查询方法、查询语法、链式操作
  17. Restful下的token认证方案
  18. phjp(ajax)作用知识点
  19. tomcat点击startup.bat一闪而退的方法
  20. Spring Boot中application.yml与bootstrap.yml的区别(转载)

热门文章

  1. Spring boot 文件路径读取异常
  2. hdu 5184(数学-卡特兰数)
  3. jquerycheckbox事件
  4. hdu5794
  5. [libgdx游戏开发教程]使用Libgdx进行游戏开发(3)-给游戏添加一些控制功能
  6. PowerDesigner用例图展示设置
  7. POJ 3237.Tree -树链剖分(边权)(边值更新、路径边权最值、区间标记)贴个板子备忘
  8. MySQL 8.0.13安装教程(windows 64位) (转)
  9. jmeter 线程组之间的参数传递
  10. Linux中安装MySql 5.7.21的详细操作步骤