1
如何強制編譯器不重載toString?我得到的最接近的是使用never類型,但從來沒有被允許隱式賦值給var,編譯器只會在變量完成某些操作時發出抱怨。誰會記得顯式聲明toString調用爲字符串?爲toString強制執行類型簽名
type ArrayToStringMethod = {
(this: { join(a: string): string, length: number }): string
(this: any): never // if this overload isn't here typescript uses
// Object.toString automatically.
}
type ArrayDontMutate<t> = {
toString: ArrayToStringMethod
readonly [index: number]: t
readonly length: number
} &
Pick<
Array<t>,
'find' |
'map' |
//'join' | deliberately removed to make toString fail
'some' |
'slice' |
'concat' |
'reduce'>
let a:ArrayDontMutate<string> =['a','b','c'] as any
let b = a.toString() //should fail no join method. b is the never type