鍍金池/ 問答/HTML/ TS 如何聲明函數(shù)對象?

TS 如何聲明函數(shù)對象?

例如:

interface A {
  (a: number): number
}

interface B extends A {
  b: string
}

const X: B = (a) => {
  return a
}

X(1)
X.b = 'x'

請問如何創(chuàng)建符合 B 接口約定的對象呢?

回答
編輯回答
萌面人

https://www.typescriptlang.or...
Hybrid Types

interface A {
    (a: number): number
}

interface B extends A {
    b: string
}
function getB(): B {
    var b = <B>function (a) {
        return a
    };
    b.b = 'x';
    return b;
}
const x = getB();

官方的例子用的是強(qiáng)制類型轉(zhuǎn)換

2018年3月1日 23:20
編輯回答
陌顏
const x: B = Object.assign(
  (a: number) => a,
  {
    b: "string"
  }
)
2018年9月4日 17:18