這是一個方法定義:
// aFunc.ts
const aFunc = async (input: string) => {
return { name: input };
};
export default aFunc;
我想在另一個檔案中使用這個函式的型別import type:
import type aFunc from './aFunc';
type API = {
getName: aFunc;
};
使用它時'aFunc' refers to a value, but is being used as a type here. Did you mean 'typeof aFunc'?出現錯誤。
我錯過了什么?是否有啟用此功能的 tsconfig 選項?我正在使用 TypeScript 4.5.5。
uj5u.com熱心網友回復:
匯入型別資訊的正確語法是以下之一:
// type modifier on import names (for mixing with value imports):
import {type Type} from './module';
// importing exclusively types in the statement:
import type {Type} from './module';
在您的示例中執行此操作的方法是創建要匯出的型別,以便您可以將其匯入另一個模塊:
TS游樂場
// aFunc.ts
export type AFunc = <T extends string>(input: T) => Promise<{ name: T }>;
const aFunc: AFunc = async name => ({ name });
// Or, you could write it like this:
// const aFunc = async <T extends string>(input: T) => ({ name: input });
// export type AFunc = typeof aFunc;
export default aFunc;
// module.ts
import {type AFunc} from './aFunc';
type API = {
getName: AFunc;
};
編輯:
您可以在匯入值時使用 import 修飾符僅匯入與值相關的型別資訊type......但是,這僅意味著您無權訪問該值(但您仍然可以使用其與型別相關的資訊) :
// lowercase aFunc is the function value which is exported as the default export in your example:
import {type default as aFunc} from './aFunc';
type API = {
getName: typeof aFunc;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/428566.html
標籤:打字稿
上一篇:當TypeScriptarg的GraphQLarg指示可為空的true時,TypeScriptarg旁邊的問號是什么?
