为什么我不能在Typescript中扩展'any'?

时间:2016-05-19 13:44:51

标签: typescript typescript1.8

我想为使用外部库的类创建一个占位符接口。所以我做了:

int tempVar = (int)buff[1];
_ret[i++] = tempVar;

我宁愿这样做并稍后添加方法(例如findAll()),而不是将我的所有类标记为'any',并且必须在以后使用'IDatabaseModel'手动搜索并替换数百个特定位置的'any'。 / p>

但编译器抱怨它无法找到'any'。

我做错了什么?

4 个答案:

答案 0 :(得分:9)

使用any

的别名
  

我想制作一个占位符界面

使用别名:

type IDatabaseModel = any;

或带索引签名[2017年8月编辑]

Since TypeScript 2.2,允许使用索引签名的属性访问语法obj.propName

interface AnyProperties {
    [prop: string]: any
}

type MyType = AnyProperties & {
    findAll(): string[]
}

let a: MyType
a.findAll() // OK, with autocomplete
a.abc = 12 // OK, but no autocomplete

答案 1 :(得分:2)

any类型是一种选择退出类型检查的方法,因此在完成类型检查的环境中使用它是没有意义的。

我建议您在使用时将方法添加到界面中:

export interface IDatabaseModel
{
    findAll(): any;
}

答案 2 :(得分:1)

"任何"是一种类型,与其他基本类型不同,它似乎没有界面。鉴于它是各种各样的通配符,我无法想象什么是"任何"可以包括。

答案 3 :(得分:1)

2020年TLDR:

而不是export default function ComboBox() { const ref0 = useRef(); return ( <Autocomplete id="combo-box-demo" ref={ref0} name="movies" options={top100Films} getOptionLabel={option => option.title} onInputChange={(e, v, r) => { const ev = e.target; if (r === "reset") console.log(ev, v, r); }} onChange={(e, v, r) => { console.log(ref0.current.getAttribute("name")); }} style={{ width: 300 }} renderInput={params => ( <TextField name="auto-input" {...params} label="Combo box" variant="outlined" /> )} /> ); } ,请尝试extends any

长版:

在某些情况下,extends Record<string, any>在TypeScript中仍然有效。但是,在TypeScript 3.9中,it is interpreted in a more conservative way

@Paleo在他的答案中创建了extends any界面。现在可以将Record改写为AnyProperties

相关问题