【发布时间】:2019-01-31 23:15:31
【问题描述】:
例如,
type User = {
first_name: string,
last_name: string,
notes: string
}
以下哪项可行?
const users:Partial<User>[] = [{first_name: "Name"}]; // A
const users:Partial<User[]> = [{first_name: "Name"}]; // B
const users:[Partial<User>] = [{first_name: "Name"}]; // C
奇怪的是,所有这些在编译时似乎都是有效的 TypeScript。
提前致谢。
【问题讨论】:
-
它只是一个部分
users的数组。 (例如const users: Partial<User>[] = [{ first_name: 'Name' }]; -
@bradcush 所以,
Option A?这就是我最初的结果,然后出现了一堆 TypeScript 错误! -
您还应该使用“接口”而不是“类型别名”,这可能是您的问题。
-
@bradcush 何时使用
type? -
有a detailed post by Martin Hochel explaining the difference between types and interfaces in TypeScript 2.7,所以我会让它来解释,但是当您需要union types 时,您可以从使用类型中受益的一个常见用例。 (例如
type something = string | number;)
标签: typescript typescript-typings typescript2.0