成员的多种类型签名,TypeScript 中的联合类型 [英] Multiple type signatures for members, Union Types in TypeScript

查看:39
本文介绍了成员的多种类型签名,TypeScript 中的联合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个可能是字符串或布尔值的属性,我该如何定义它:

If I have a property that might be a string or a boolean how do I define it:

interface Foo{
    bar:string;
    bar:boolean;
}

我不想诉诸:

interface Foo{
    bar:any;
}

如果没有any,我认为这是不可能的.您可以回答以下任一问题:

I don't think its possible without any. You can answer any of these:

我是否忽略了规范及其现在的可能?有这样的计划吗?是否记录了功能请求?

Have I overlooked a spec and its possible right now? Is something like this planned? Has a feature request been logged?

我会想象这样的事情:

interface Foo{
    bar:string;
    bar:boolean;
    bar:any; 
}

var x:Foo = <any>{};
x.bar="asdf";
x.bar.toUpperCase(); // intellisence only for string 

推荐答案

这通常被称为联合类型".1.4 中的 TypeScript 类型系统确实允许这样做.

This is usually referred to as "union types". The TypeScript type system from 1.4 does allow for this.

请参阅:高级类型

这篇关于成员的多种类型签名,TypeScript 中的联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆