如果我有一个接口:
type IData =
abstract member firstName: string
abstract member lastName: string
Run Code Online (Sandbox Code Playgroud)
如何定义符合此接口的记录类型。
我试过如下:
> type Data = { firstName: string; lastName: string } interface IData ;;
Snippet.js(43,63): error FS0366: No implementation was given for 'abstract member IData.firstName : string'. Note that all interface members must be implemented
and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'.
Run Code Online (Sandbox Code Playgroud)
来自Records的官方参考:
记录字段与类的不同之处在于它们自动公开为属性
我的第一个问题是:如果属性是“自动公开的”,那么为什么我需要“做某事”来实现它们。
由于错误消息要求我提供接口的实现,因此我尝试了以下操作:
> type Data = { firstName: string; lastName: string; } interface IData with
- member this.firstName with get () = this.firstName
- member this.lastName with get () = this.lastName
type Data =
{firstName: string;
lastName: string;}
with
interface IData
end
Run Code Online (Sandbox Code Playgroud)
到目前为止一切顺利,但是现在当我尝试使用它时,我遇到了问题:
> let d: IData = { firstName = "john"; lastName = "doe" } ;;
error FS0001: This expression was expected to have type
'IData'
but here has type
'Data'
Run Code Online (Sandbox Code Playgroud)
另一种尝试:
> let d = { firstName = "john"; lastName = "doe" }
- ;;
val d : Data = {firstName = "john";
lastName = "doe";}
> let d2: IData = d ;;
C:\Users\loref\Workspace\source-nly10r\Untitled-1(25,17): error FS0001: This expression was expected to have type
'IData'
but here has type
'Data'
Run Code Online (Sandbox Code Playgroud)
所以,我的第二个问题是,如果Data
实现,IData
那么为什么我不能将Data
type的值分配给type 的变量IData
?
正如Gustavo所指出的,隐式接口实现正在由 F# 实现者讨论,目前尚不可用。
写的。我的第二个问题,需要显式转换:
> let d2: IData = d :> IData ;;
val d2 : IData = {firstName = "john";
lastName = "doe";}
Run Code Online (Sandbox Code Playgroud)