type myType = 'A';
const myVar = 'A';
let a: 'A'; // OK
let b: myType; // OK
let c: myVar; // ERROR : cannot find name 'myVar'为什么不能使用var作为类型?这不应该是可能的吗?
发布于 2018-01-05 17:13:13
myVar是常量,您不能将变量键入为常量,您可以指定变量与常量具有相同的类型:
let c: typeof myVar;请注意,由于常量是"A“,因此上面的声明与
let c: "A";因此,唯一可赋值的tp c是常量值"A"
发布于 2018-01-05 17:15:08
有4种方法可以在TypeScript中解除对变量的保护
var, let, const & Type (Type will be custom datatype)
let & var非常相似,而const可以防止重新赋值给变量。您可以在var和let here之间找到不同之处。
const是一个常量,它在TypeScript中的行为与C#相同。在C#中,我们也不能使用const作为类型。
myVar是一个变量,而不是类型,所以你不能使用变量作为类型。
https://stackoverflow.com/questions/48110390
复制相似问题