我试图扩展基号类型并添加一些自定义原型:
核心文件如下所示:
tsconfig.json:
...
"typeRoots": [
"node_modules/@types",
"types"
]
...types/number.d.ts:
export {}
declare global {
interface Number {
isInt() : () => any
}
}number.extension.ts:
Number.prototype.isInt = function() {
return (Math.round(this) == this)
}当我试图编译时,我会发现错误:
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;..。还有更多。
发布于 2021-03-26 06:12:59
它的工作(ts游乐场):
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()) // falsehttps://stackoverflow.com/questions/66810787
复制相似问题