成员的多种类型签名,TypeScript 中的联合类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18006045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple type signatures for members, Union Types in TypeScript
提问by basarat
If I have a property that might be a string or a boolean how do I define it:
如果我有一个可能是字符串或布尔值的属性,我该如何定义它:
interface Foo{
bar:string;
bar:boolean;
}
I don't want to resort to:
我不想诉诸:
interface Foo{
bar:any;
}
I don't think its possible without any
. You can answer any of these:
我认为没有any
. 您可以回答以下任一问题:
Have I overlooked a spec and its possible right now? Is something like this planned? Has a feature request been logged: http://typescript.codeplex.com/workitem/list/basic? (UPDATEthis is the issue report you can vote on https://typescript.codeplex.com/workitem/1364)
我现在是否忽略了规范及其可能?有这样的计划吗?是否记录了功能请求:http: //typescript.codeplex.com/workitem/list/basic?(更新这是您可以在https://typescript.codeplex.com/workitem/1364 上投票的问题报告)
I would imagine something like this:
我会想象这样的事情:
interface Foo{
bar:string;
bar:boolean;
bar:any;
}
var x:Foo = <any>{};
x.bar="asdf";
x.bar.toUpperCase(); // intellisence only for string
采纳答案by Ryan Cavanaugh
This is usually referred to as "union types". The TypeScript type system from 1.4 does allow for this.
这通常称为“联合类型”。1.4 中的 TypeScript 类型系统确实允许这样做。
See: Advanced Types
请参阅:高级类型
回答by MarcG
As of 2015, union-types work:
截至 2015 年,联合类型工作:
interface Foo {
bar:string|boolean;
}
回答by Damian
Not saying this answers your question, but could you resort to something like this?
不是说这回答了你的问题,但你能诉诸于这样的事情吗?
interface Foo<T>{
bar:T;
}
function createFoo<T>(bar:T) : Foo<T>{
return {bar:bar};
}
var sFoo = createFoo("s");
var len = sFoo.bar.length;
var bFoo = createFoo(true);
var result = bFoo.bar === true;