gpt4 book ai didi

TypeScript 3.0 `unknown` 类型作为 `any` 或 `generics` 的替代?

转载 作者:行者123 更新时间:2023-12-04 11:45:40 24 4
gpt4 key购买 nike

https://blogs.msdn.microsoft.com/typescript/2018/07/12/announcing-typescript-3-0-rc/#the-unknown-type

TypeScript 3.0 introduces a new type called unknown that does exactly that. 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.

As an example, swapping the above example to use unknown instead of any forces turns all usages of foo into an error:

let foo: unknown = 10;

// Since `foo` has type `unknown`, TypeScript
// errors on each of these usages.
foo.x.prop;
foo.y.prop;
foo.z.prop;
foo();
new foo();
upperCase(foo);
foo `hello world!`;

function upperCase(x: string) {
return x.toUpperCase();
}
我最近开始用 TypeScript 编写代码,这里是我的问题:
1. 在我看来, unknown可以完全替代 any .
当然,用原生 JavaScript 编写的代码需要使用 any在 TypeScript 中自动输入,但是当我们从头开始用纯 TypeScript 编写代码时,还有什么理由使用 any输入而不是 unknown从 3.0 版开始?
2. unknown有什么区别和 generics ?
例如,
const A = <T>(value: T): T => value;
const A1 = (value: unknown) => value;

console.log(A<string>('Hello'), A<number>(100));



const B = <T, U>(t: T, u: U) => {
console.log(t);
console.log(u);
};
const B1 = (t: unknown, u: unknown) => {
console.log(t);
console.log(u);
};

B<string, number>('Hello', 100);
B<number, string>(100, 'Hello');
并假设参数 value: unknown最初是绝对类型的,值的类型是确定的,所以在我看来没有理由通过 T明确地。
谢谢。

最佳答案

关于你问题的第一部分,我可能会使用 unknown而不是 any在大多数情况下,最好在必要时使用明确的断言,以使程序员意识到某些事情不一定安全。 any 的一个大问题人们是否在不知不觉中将其分配给预期错误的类型变量或参数:

function foo() :any { return 1;} 
let x:string = foo () ;
x.bold() // runtime error

使用上述任何代码都会导致运行时错误
function foo() : unknown { return 1;} 
let x:string = foo () ; // compile time error we need to think about why we are doing this.

使用上面的代码,我们必须使用显式断言才能使其工作,并考虑为什么我们要断言 foo 的结果。成为字符串

也许这个 answer关于两者之间的差异也有帮助

关于这个作为泛型的替代品,它不是。首先,您应该避免指定显式类型参数,大多数情况下编译器会为您推断它们。
const A = <T>(value: T): T => value;
const A1 = (value: unknown) => value;

// redundant and a lot of typing
console.log(A<string>('Hello'), A<number>(100));
// let the compiler do the work for us
console.log(A('Hello'), A(100))

如果您仅在一个位置使用泛型参数(即用于单个参数或用于返回值),则不会显示泛型的威力,而是当您使用它来指定两个或多个之间的关系时。

例如您的 A例子 :
 A('').bold() // ok return is the same as the parameter type

A1('').bold() //error return value is of type unknown

或为 B我们可以指定参数必须是相同类型的
const B = <T>(t: T, u: T) => {
console.log(t);
console.log(u);
};
const B1 = (t: unknown, u: unknown) => {
console.log(t);
console.log(u);
};

B('Hello', 100); //compile time error
B1(100, 'Hello'); //compiles

此外,泛型参数可以有额外的约束,因此并非所有类型都对给定的类型参数有效。

关于TypeScript 3.0 `unknown` 类型作为 `any` 或 `generics` 的替代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51569567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com