首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何扩展打字本中的基号类型?

如何扩展打字本中的基号类型?
EN

Stack Overflow用户
提问于 2021-03-26 03:49:18
回答 1查看 77关注 0票数 1

我试图扩展基号类型并添加一些自定义原型:

核心文件如下所示:

tsconfig.json:

代码语言:javascript
复制
...

"typeRoots": [
    "node_modules/@types",
    "types"
]

...

types/number.d.ts:

代码语言:javascript
复制
export {}

declare global {
    interface Number {
        isInt() : () => any
    }
}

number.extension.ts:

代码语言:javascript
复制
Number.prototype.isInt = function() {
    return (Math.round(this) == this)
}

当我试图编译时,我会发现错误:

代码语言:javascript
复制
Error: number.extensions.ts:16:18 - error TS2339: Property 'isInt' does not exist on type 'Number'.
[ng] 16 Number.prototype.isInt = function() {
[ng]                     ~~~~~
[ng] Error: node_modules/typescript/lib/lib.es5.d.ts:395:5 - error TS2300: Duplicate identifier 'trimMiddle'.
[ng] 395     trimMiddle: () => any;
[ng]         ~~~~~~~~~~
[ng] Error: node_modules/typescript/lib/lib.es5.d.ts:396:5 - error TS2411: Property 'anchor' of type '(name: string) => string' is not assignable to string index type '() => any'.
[ng] 396     [x: string]: () => any;
[ng]         ~~~~~~~~~~~~~~~~~~~~~~~
[ng] Error: node_modules/typescript/lib/lib.es5.d.ts:396:5 - error TS2411: Property 'charAt' of type '(pos: number) => string' is not assignable to string index type '() => any'.
[ng] 396     [x: string]: () => any;
[ng]         ~~~~~~~~~~~~~~~~~~~~~~~
[ng] Error: node_modules/typescript/lib/lib.es5.d.ts:396:5 - error TS2411: Property 'charCodeAt' of type '(index: number) => number' is not assignable to string index type '() => any'.
[ng] 396     [x: string]: () => any;

..。还有更多。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-26 06:12:59

它的工作(ts游乐场):

代码语言:javascript
复制
export {}
declare global {
    interface Number {
        isInt: () =>  boolean // type is 'boolean', not 'any'
    }
}

Number.prototype.isInt = function():boolean {
    // we must cast Number to number via Number(this)
    return (Math.round(Number(this)) == this) 
}

let x: Number = 10;
let y: Number = 10.2;
console.log(x.isInt()) // true
console.log(y.isInt()) // false
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66810787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档