typescript檔案談到了函式呼叫簽名和構造簽名,并描述了你如何宣告型別和使用它。https://www.typescriptlang.org/docs/handbook/2/functions.html#call-signatures
呼叫簽名(沒有實作一個型別為DescribableFunction的函式)
type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn。 description " returned " fn(6) )。)
構造簽名(沒有實作型別為SomeConstructor的函式)
type SomeConstructor = {
new(s: string)。SomeObject;
};
function fn(ctor: SomeConstructor) {
return new ctor("hello"/span>) 。
但它從未顯示如何定義此類函式的實際實作。而且我找了很多天,似乎也找不到這方面的東西。如果有一個簡單的例子,說明如何使用以及何時使用,將對理解這些概念很有幫助。
我試影像這樣做呼叫簽名,但顯然它拋出了錯誤
type DescribableFunction = {
description: string;
(str: string): string;
}
const df: DescribableFunction = {
description: 'df function description',
(str: string): {
return str;
}
}
console.log(df.description, df('hello world'))。
uj5u.com熱心網友回復:
沒有 "字面 "的語法來宣告一個具有額外屬性的函式。 但函式是正常的物件,可以向其添加屬性:
const df: DescribableFunction = (str: string) => {
return str;
}
df.description = "df function description"。
通常情況下,Typescript會抱怨屬性description在df的初始宣告中缺失,但看起來它對函式做了例外處理,允許在以后添加它們。
至于建構式簽名,它們很好地映射到類語法。以下面的例子為例:
type CacheableConstructor = {
new(s: string): { x: number };
cached: boolean
};
它可以這樣實作:
class SomeCC {
static cached = false
x: 數字
constructor(s: string) {}。
}
//檢查是否符合建構式的標志。
const cc: CacheableConstructor = SomeCC
uj5u.com熱心網友回復:
實際上,Object.assign有一個簽名,回傳其引數的截距型別
Object。 assign<T,U>( t: T, u: U ) : T & U
那么它就可以是
type DescribableFunction = {
description: string;
(str: string): string;
}
const df: DescribableFunction = Object.assign(
(str: string) => str。
{ description: 'df function description' },
);
console.log(df.description, df('hello world') ) 。
//works
這有一個缺點,它只在你將描述分配給函式時起作用,而不是反過來,盡管TypeScript對兩者都有型別。
// types正確但不作業(原因很明顯)
型別 DescribableFunction = {
description: string;
(str: string): string;
}
const df: DescribableFunction = Object.assign(
{ description: 'df function description' },
(str: string) => str。
);
console.log(df.description, df('hello world'))。
// df不是一個函式。
uj5u.com熱心網友回復:
我自己并不知道這一點,但實際上編譯器會在創建函式后檢查你是否設定了description屬性:
type DescribableFunction = {
description: string;
(str: string): string;
}
const df: DescribableFunction = (str: string) => {
return str;
}
//如果你注釋掉下面這行,編譯器會抱怨。
df.description = 'df function description'。
console.log(df.description, df('hello world') ) 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/307928.html
標籤:
上一篇:在TypeScript中實作GraphQL服務器的最佳方式是什么?
下一篇:將給定的陣列型別解構為新的型別
