天道酬勤,学无止境

'unknown' vs. 'any'

TypeScript 3.0 introduces unknown type, according to their wiki:

unknown is now a reserved type name, as it is now a built-in type. Depending on your intended use of unknown, you may want to remove the declaration entirely (favoring the newly introduced unknown type), or rename it to something else.

What is difference between unknown and any? When should we use unknown over any?

评论

You can read more about unknown in the PR or the RC announcement, but the gist of it is:

[..] unknown which is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.

A few example:

let vAny: any = 10;          // We can assign anything to any
let vUnknown: unknown =  10; // We can assign anything to unknown just like any 


let s1: string = vAny;     // Any is assignable to anything 
let s2: string = vUnknown; // Invalid we can't assign vUnknown to any other type (without an explicit assertion)

vAny.method();     // ok anything goes with any
vUnknown.method(); // not ok, we don't know anything about this variable

The suggested usage is:

There are often times where we want to describe the least-capable type in TypeScript. This is useful for APIs that want to signal “this can be any value, so you must perform some type of checking before you use it”. This forces users to safely introspect returned values.

The difference between unknown and any is described as:

Much like any, any value is assignable to unknown; however, unlike any, you cannot access any properties on values with the type unknown, nor can you call/construct them. Furthermore, values of type unknown can only be assigned to unknown or any.

To answer your question of when should you use unknown over any:

This is useful for APIs that want to signal “this can be any value, so you must perform some type of checking before you use it”. This forces users to safely introspect returned values.

Take a look at the TypeScript 3.0 announcement for examples of type checking a variable of type unknown and a more detailed explanation.

any type:

The any type represents all possible JS values. Every type is assignable to type any. Therefore the type any is an universal supertype of the type system. The TS compiler will allow any operation on values typed any. For example:

let myVar: any;

myVar[0];
myVar();
myVar.length;
new myVar();

In many occasions this is too lenient of the TS compiler. i.e. it will allow operations which we could have known to be resulting into a runtime error.

unknown type:

The unknown type represents (just like any) all possible JS values. Every type is assignable to type unknown. Therefore the type unknown is another universal supertype of the type system (alongside any). However, the TS compiler won't allow any operation on values typed unknown. Furthermore, the unknown type is only assignable to the type any. An example will clarify this:

let myVar: unknown;

let myVar1: unknown = myVar;   // No error
let myVar2: any = myVar;       // No error
let myVar3: boolean = myVar;   // Type 'unknown' is not assignable to type 'boolean'

// The following operations on myVar all give the error:
// Object is of type 'unknown'
myVar[0];
myVar();
myVar.length;
new myVar();

any, unknown:

  • allows to assign any type

any:

  • allows to be assigned to any type
  • does allow to call any method

unknown:

  • doesn't allow to be assigned to any type
  • doesn't allow to call any method
const a: any = 'a'; // OK
const b: unknown = 'b' // OK

const v1: string = a; // OK
const v2: string = b; // ERROR
const v3: string = b as string; // OK

a.trim() // OK
b.trim() // ERROR

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • “未知”与“任何”('unknown' vs. 'any')
    问题 根据他们的Wiki,TypeScript 3.0引入了unknown类型: 未知现在是保留类型名称,因为它现在是内置类型。 根据未知的预期用途,您可能希望完全删除声明(支持新引入的未知类型),或将其重命名为其他名称。 unknown和any和any什么不一样? 我们什么时候应该使用unknown过any ? 回答1 您可以在PR或RC公告中阅读有关unknown更多信息,但要点是: [..] unknown是任何类型安全的对应物。 任何东西都可以分配给未知对象,但是除了自身以及没有类型声明或基于控制流的缩小对象之外,任何东西都不能分配给其他对象。 同样,在未先声明或缩小为更具体的类型之前,不允许对未知数执行任何操作。 几个例子: let vAny: any = 10; // We can assign anything to any let vUnknown: unknown = 10; // We can assign anything to unknown just like any let s1: string = vAny; // Any is assignable to anything let s2: string = vUnknown; // Invalid we can't assign vUnknown to any other type (without
  • Angular 里 unknown 和 any 的区别
    在SAP Spartacus项目里,我们定义的一个配置对象refreshFocus 属性的类型,为unknown: 这个StackOverflow讨论对于unknown和any的区别做了比较清楚的阐述: https://stackoverflow.com/questions/51439843/unknown-vs-any unknown which is the type-safe counterpart of any. unknown 和 any 相比,多了类型安全特性。 Anything is assignable to unknown, but unknown isn’t assignable to anything but itself and any without a type assertion or a control flow based narrowing. 任何值都能赋给类型为unknown的变量,但是unknown不能赋值给任何除了unknown类型之外的其他类型的变量。 Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type
  • Optimizing Excel formulas - SUMPRODUCT vs SUMIFS/COUNTIFS
    According to a couple of web sites, SUMIFS and COUNTIFS are faster than SUMPRODUCT (for example: http://exceluser.com/blog/483/excels-sumifs-or-sumproduct-which-is-faster.html). I have a worksheet with an unknown number of rows (around 200 000) and I'm calculating performance reports with the numbers. I have over 6000 times almost identical SUMPRODUCT formulas with a couple of difference each times (only the conditions change). Here is an example of what I got: =IF(AFO4>0, (SUMPRODUCT((Sheet1!$N:$N=$A4) *(LEFT(Sheet1!$H:$H,2)="1A") *(Sheet1!$M:$M<>"service catalog") *(Sheet1!$J:$J="incident")
  • 不存在vs不存在(NOT IN vs NOT EXISTS)
    问题 这些查询中哪个更快? 不存在: SELECT ProductID, ProductName FROM Northwind..Products p WHERE NOT EXISTS ( SELECT 1 FROM Northwind..[Order Details] od WHERE p.ProductId = od.ProductId) 或不在: SELECT ProductID, ProductName FROM Northwind..Products p WHERE p.ProductID NOT IN ( SELECT ProductID FROM Northwind..[Order Details]) 查询执行计划说他们都做同样的事情。 如果是这样,建议使用哪种形式? 这基于NorthWind数据库。 [编辑] 刚刚发现这篇有用的文章:http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx 我想我会坚持不存在。 回答1 我总是默认为NOT EXISTS 。 目前执行计划可能相同,但是如果将来更改任一列以允许NULL则NOT IN版本将需要做更多的工作(即使数据中实际上没有NULL ),并且无论如何,如果存在NULL则NOT IN不太可能是您想要的。 当Products.ProductID或
  • 为什么String.valueOf(null)抛出NullPointerException?(Why does String.valueOf(null) throw a NullPointerException?)
    问题 根据文档,方法String.valueOf(Object obj)返回: 如果参数为null ,则字符串等于"null" ; 否则,返回obj.toString()的值。 但是,当我尝试这样做时,怎么会这样: System.out.println("String.valueOf(null) = " + String.valueOf(null)); 它会抛出NPE吗? (如果您不相信,请自己尝试!) Exception in thread "main" java.lang.NullPointerException at java.lang.String.(Unknown Source) at java.lang.String.valueOf(Unknown Source) 怎么会这样呢? 这些文件在骗我吗? 这是Java中的主要错误吗? 回答1 问题是String.valueOf方法已重载: String.valueOf(Object) String.valueOf(char []) Java规范语言要求在这种情况下,选择最具体的重载: JLS 15.12.2.5选择最具体的方法 如果多个成员方法既可访问又可应用于方法调用,则必须选择一个成员方法来为运行时方法分派提供描述符。 Java编程语言使用选择最特定方法的规则。 char[]是Object
  • C : typedef struct name {…}; VS typedef struct{…} name;
    As the title says, I have this code: typedef struct Book{ int id; char title[256]; char summary[2048]; int numberOfAuthors; struct Author *authors; }; typedef struct Author{ char firstName[56]; char lastName[56]; }; typedef struct Books{ struct Book *arr; int numberOfBooks; }; I get these errors from gcc : bookstore.c:8:2: error: unknown type name ‘Author’ bookstore.c:9:1: warning: useless storage class specifier in empty declaration [enabled by default] bookstore.c:15:1: warning: useless storage class specifier in empty declaration [enabled by default] bookstore.c:21:2: error: unknown type
  • const vs constexpr的变量(const vs constexpr on variables)
    问题 以下定义之间有区别吗? const double PI = 3.141592653589793; constexpr double PI = 3.141592653589793; 如果不是,在C ++ 11中首选哪种样式? 回答1 我相信有区别。 让我们重命名它们,以便我们可以更轻松地讨论它们: const double PI1 = 3.141592653589793; constexpr double PI2 = 3.141592653589793; PI1和PI2都是常量,这意味着您无法对其进行修改。 但是,只有PI2是编译时常量。 它应在编译时初始化。 PI1可以在编译时或运行时初始化。 此外,在需要编译时常数的上下文中,只能使用PI2 。 例如: constexpr double PI3 = PI1; // error 但: constexpr double PI3 = PI2; // ok 和: static_assert(PI1 == 3.141592653589793, ""); // error 但: static_assert(PI2 == 3.141592653589793, ""); // ok 至于您应该使用哪个? 使用满足您需求的任何一种。 是否要确保您有一个可在需要编译时常数的上下文中使用的编译时常数?
  • [caffe]: check fails: Check failed: hdf_blobs_[i]->shape(0) == num (200 vs. 6000)
    I have the train and label data as data.mat. (I have 200 training data with 6000 features and labels are (-1, +1) that have saved in data.mat). I am trying to convert my data in hdf5 and run Caffe using: load data.mat hdf5write('my_data.h5', '/new_train_x', single( reshape(new_train_x,[200, 6000, 1, 1]) ) ); hdf5write('my_data.h5', '/label_train', single( reshape(label_train,[200, 1, 1, 1]) ), 'WriteMode', 'append' ); And my layer.prototxt (just data layer) is: layer { type: "HDF5Data" name: "data" top: "new_train_x" # note: same name as in HDF5 top: "label_train" # hdf5_data_param { source: "
  • 如何在C条件预处理器指令中比较字符串(How to compare strings in C conditional preprocessor-directives)
    问题 我必须在C中执行类似的操作。仅当使用char时,它才有效,但是我需要一个字符串。 我怎样才能做到这一点? #define USER "jack" // jack or queen #if USER == "jack" #define USER_VS "queen" #elif USER == "queen" #define USER_VS "jack" #endif 回答1 我不认为有一种方法可以在预处理程序指令中完全进行可变长度字符串比较。 您也许可以执行以下操作: #define USER_JACK 1 #define USER_QUEEN 2 #define USER USER_JACK #if USER == USER_JACK #define USER_VS USER_QUEEN #elif USER == USER_QUEEN #define USER_VS USER_JACK #endif 或者,您可以稍微重构代码,而改用C代码。 回答2 [更新:2021.01.04] 自从我2014年首次发布此内容以来,发生了一件改变,是#pragma message的格式。 如今,必须要有括号! #pragma message ("USER IS " USER) #pragma message ("USER_VS IS " USER_VS) 就是说,2016代码(使用字¬
  • OpenCV SURF function is not implemented
    When I try to run the sample find_obj.cpp or any OpenCV SURF program I get the following error in command prompt while executing the code. The project builds without errors and warnings. I am using VS2011 beta, OpenCV 2.4 and windows7. Error message: OpenCV Error: The function/feature is not implemented < OpenCV was built without SURF support> in unknown function,file ..\..\..\src\opencv\modules\legacy\src\features2d.cpp, line 77 I tried to build the OpenCV 2.4 again using Cmake and then VS2011 in debug mode and then added the lib paths in the IDE, but still no result. How can I fix that?
  • LogisticRegression: Unknown label type: 'continuous' using sklearn in python
    I have the following code to test some of most popular ML algorithms of sklearn python library: import numpy as np from sklearn import metrics, svm from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC trainingData = np.array([ [2.3, 4.3, 2.5], [1.3, 5.2, 5.2], [3.3, 2.9, 0.8], [3.1, 4.3, 4.0] ]) trainingScores
  • Are HLists nothing more than a convoluted way of writing tuples?
    I am really interested in finding out where the differences are, and more generally, to identify canonical use cases where HLists cannot be used (or rather, don't yield any benefits over regular lists). (I am aware that there are 22 (I believe) TupleN in Scala, whereas one only needs a single HList, but that is not the kind of conceptual difference I am interested in.) I've marked a couple of questions in the text below. It might not actually be necessary to answer them, they are more meant to point out things that are unclear to me, and to guide the discussion in certain directions
  • How to undestand relations between types any, unknown, {} and between them and other types?
    Trying to understand relations between types I have this code type CheckIfExtends<A, B> = A extends B ? true : false; type T1 = CheckIfExtends<number, unknown>; //true type T2 = CheckIfExtends<number, {}>; //true type T3 = CheckIfExtends<number, any>; //true type T4 = CheckIfExtends<() => void, unknown>; //true type T5 = CheckIfExtends<() => void, {}>; //true type T6 = CheckIfExtends<() => void, any>; //true type T7 = CheckIfExtends<unknown, any>; //true type T8 = CheckIfExtends<any, unknown>; //true type T9 = CheckIfExtends<{}, unknown>; //true type T10 = CheckIfExtends<{}, any>; //true type
  • Simple Java program 100 times slower after plugging in USB hotspot
    I have following Java program: class Main { public static void main(String[] args) throws java.io.IOException { long start = System.nanoTime(); java.io.File.createTempFile("java_test", ".txt").delete(); System.out.println((System.nanoTime() - start ) / 1e9); } } Normally, it takes bout 63 miliseconds to execute: $ java Main 0.06308555 But, once I connect Android phone as USB hotspot, it takes significantly longer. Depending on the machine anywhere from 3 to 40 seconds: $ java Main 4.263285528 The strange thing is that nothing here is actually transferred over the network - plugged network
  • ArrayList vs List<object>
    I saw this reply from Jon on Initialize generic object with unknown type: If you want a single collection to contain multiple unrelated types of values, however, you will have to use List<object> I'm not comparing ArrayList vs List<>, but ArrayList vs List<object>, as both will be exposing elements of type object. What would be the benefit of using either one in this case? EDIT: It's no concern for type safety here, since both class is exposing object as its item. One still needs to cast from object to the desired type. I'm more interested in anything other than type safety. EDIT: Thanks Marc
  • [完美解决]VS2012创建或打开C++浏览数据库文件时出现错误
    [完美解决]VS2012创建或打开C++浏览数据库文件时出现错误 在使用VC2012的时候出现问题如下: 创建或打开C++浏览数据库文件XXXXXXX.stdf时发生错误。IntelliSense和浏览信息将不能用于C++项目。 请确保已安装Microsoft SQL Server Compact4.0,并且没有其他应用程序正在访问文件。如果仍然存在问题,请删除并重新打开解决方案。 出现如下错误可能不会影响你打代码,但是会没有提示之类的。 当出现此问题时,说明你没有安装Compact4.0 可以去下载或者找到安装光盘的\packages\SSCE40里运行SSCERuntime_x64-enu.exe 运行次项会安装,如果安装时出现错误1402无法打开键UNKNOWN、Components\A8CD4AD91379E0F3B85DCF71AC8684DA\8F229D7349097C4489AD1CC097FE08DC 类似如下的错误码,可以打开注册表,找到此路径: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\A8CD4AD91379E0F3B85DCF71AC8684DA
  • SQL NOT IN不起作用(SQL NOT IN not working)
    问题 我有两个数据库,一个数据库保存库存,另一个数据库包含主数据库记录的子集。 以下SQL语句不起作用: SELECT stock.IdStock ,stock.Descr FROM [Inventory].[dbo].[Stock] stock WHERE stock.IdStock NOT IN (SELECT foreignStockId FROM [Subset].[dbo].[Products]) 不在中不起作用。 删除NOT会给出正确的结果,即两个数据库中都有产品。 但是,使用NOT IN根本不会返回任何结果。 我在做什么错,有什么想法吗? 回答1 SELECT foreignStockId FROM [Subset].[dbo].[Products] 可能会返回NULL 。 如果NOT IN值列表中存在任何NULL则NOT IN查询将不返回任何行。 您可以使用IS NOT NULL明确排除它们,如下所示。 SELECT stock.IdStock, stock.Descr FROM [Inventory].[dbo].[Stock] stock WHERE stock.IdStock NOT IN (SELECT foreignStockId FROM [Subset].[dbo].[Products] WHERE foreignStockId IS NOT NULL
  • 在C ++中确定32位和64位(Determining 32 vs 64 bit in C++)
    问题 我正在寻找一种可靠地确定C ++代码是否以32位和64位编译的方法。 我们已经提出了我们认为使用宏的合理解决方案,但是很想知道人们是否可以想到这种情况可能会失败,或者是否有更好的方法来做到这一点。 请注意,我们正在尝试在跨平台的多编译器环境中执行此操作。 #if ((ULONG_MAX) == (UINT_MAX)) # define IS32BIT #else # define IS64BIT #endif #ifdef IS64BIT DoMy64BitOperation() #else DoMy32BitOperation() #endif 谢谢。 回答1 不幸的是,没有跨平台宏可以在主要编译器中定义32/64位。 我发现执行此操作的最有效方法如下。 首先,我选择自己的代表。 我更喜欢ENVIRONMENT64 / ENVIRONMENT32。 然后,我找出所有主要的编译器用来确定它是否是64位环境的东西,然后使用它来设置我的变量。 // Check windows #if _WIN32 || _WIN64 #if _WIN64 #define ENVIRONMENT64 #else #define ENVIRONMENT32 #endif #endif // Check GCC #if __GNUC__ #if __x86_64__ || __ppc64__
  • ViewParam vs @ManagedProperty(value =“#{param.id}”)(ViewParam vs @ManagedProperty(value = “#{param.id}”))
    问题 像这样定义视图参数之间有什么区别: <f:metadata> <f:viewParam name="id" value="#{someBean.id}"/> </f:metadata> 并在ManagedBean中定义属性,如下所示: @ManagedProperty(value = "#{param.id}") private Integer id; 回答1 <f:viewParam>: 仅在更新模型值阶段设置该值(因为它扩展了UIInput)。 该设置值在@PostConstruct期间不可用,因此您需要在<f:metadata>内部附加一个<f:event type =“ preRenderView” listener =“#{bean.init}” />来进行初始化/预加载,基于设定值。 从JSF 2.2开始,您可以改为使用<f:viewAction> 。 允许嵌套<f:converter>和<f:validator>进行更细粒度的转换/验证。 甚至可以附加<h:message>。 可以使用<h:link>的includeViewParams属性或任何URL中的includeViewParams=true请求参数作为GET查询字符串包含在内。 可以在@RequestScoped bean上使用,但是如果您希望视图参数能够承受由视图中包含的表单引起的任何验证失败
  • Tensorflow - matmul of input matrix with batch data
    I have some data represented by input_x. It is a tensor of unknown size (should be inputted by batch) and each item there is of size n. input_x undergoes tf.nn.embedding_lookup, so that embed now has dimensions [?, n, m] where m is the embedding size and ? refers to the unknown batch size. This is described here: input_x = tf.placeholder(tf.int32, [None, n], name="input_x") embed = tf.nn.embedding_lookup(W, input_x) I'm now trying to multiply each sample in my input data (which is now expanded by embedding dimension) by a matrix variable, U, and I can't seem to get how to do that. I first