如何知道TypeScript中接口键的类型?



如果我有这个超级简单的界面:

interface Dog {
name: string;
}

有办法检查密钥的类型吗?例如,我们可以很容易地使用普通的var:

let hi: number = 2;
if(typeof hi === 'number') { // It's possible 
console.log('yes, it is');
}

if(typeof Dog['name'] === 'string') { // It's not possible 
console.log('yes, it is');
}

错误:'Dog' only refers to a type, but is being used as a value here.有什么建议吗?

接口在打印稿纯粹是一个编译时在运行时构造和不持续。因此,不能对编译时构造进行类型检查。

JavaScript中的typeof操作符与你在TypeScript中定义的类型没有任何关系,但会进行运行时检查。要以这种方式使用它(就像typeof hi === 'number'一样),您必须有一个类型为dog的对象:

interface Dog {
name: string;
}
const x: Dog = { name: 'Duke' };
if (typeof x['name'] === 'string') {
console.log('yes, it is');
}

这但是不会带来多大好处在这种特殊情况下因为打字稿已经确保名称是一个字符串条件总是真。

这需要TypeScript中不存在的运行时类型元信息。TypeScript可以转换成JavaScript,而JavaScript在类中没有字段类型信息之类的元数据。

所以我的回答是,直接做你要求的是不可能的。

你在TypeScript中体验到的所有复杂的类型只存在于开发阶段。

值得注意的是,在JavaScript中,你可以做一些基本的类型检查,比如:

// some empty prototype function (can be a class)
function Plant() {
}
// use the function to create an object
let x = new Plant();
// checking the type of x returns 'object'
typeof x; // this returns 'object'
// you can also check whether x was created using `Plant`
x instanceof Plant; // this returns true

最新更新