繁体   English   中英

函数中的泛型不检查Typescript中的参数类型

[英]Generic in function doesn't check argument type in Typescript

我期待打字稿会引发错误,因为我在EntryPoints传递了错误数量的元素,但它不会发生。

function createContext<T>(defaultValue: T): T[] {
  return [defaultValue]
}

interface EntryPoints {
  parentSelector: string;
}
interface SomeType {
  entryPoints: EntryPoints[];
}
const defaultData = {
  entryPoints: [{
    parentSelector: '',
    foo: 1 // <-- expecting error here
  }]
}
createContext<SomeType>(defaultData)

没有通用的相同代码按预期工作

function createContext<T>(defaultValue: T): T[] {
  return [defaultValue]
}

interface EntryPoints {
  parentSelector: string;
}
interface SomeType {
  entryPoints: EntryPoints[];
}
const defaultData: SomeType = {
  entryPoints: [{
    parentSelector: '',
    foo: 1 // <-- throwing error here
  }]
}
createContext(defaultData)

操场

您遇到了对象新鲜度问题,因此允许使用其他密钥。

如果您明确传递了该对象,则将对其进行正确的键入检查:

function createContext<T>(defaultValue: T): T[] {
  return [defaultValue];
}

interface EntryPoints {
  parentSelector: string;
}

interface SomeType {
  entryPoints: EntryPoints[];
}

createContext<SomeType>({
  entryPoints: [
    {
      parentSelector: "",
      foo: 1 // <-- errors as expected here
    }
  ]
});

TypeScript Playground

你遇到的是两者之间的区别

  1. 在将字面值分配给类型时进行类型检查
  2. 在将变量赋值给类型时进行类型检查。

考虑一下我们有两种类型。 其中一个财产比另一个财产多一个。

type Foo = {
  foo: string;
};

type FooBar = {
  foo: string;
  bar: string;
};

对象文字指定给类型时, 不允许使用其他属性

// Object literal may only specify known properties,
// and 'bar' does not exist in type 'Foo'.
const foo: Foo = {
  foo: "foo",
  bar: "bar" // <---- bar is not allowed on Foo.
};

变量分配给类型时, 允许使用其他属性

const fooBar: FooBar = {
  foo: "foo",
  bar: "bar" // <---- bar is going to be allowed on Foo
};

const foo: Foo = fooBar; // <---- see, no error

fooBar分配给foo是可以的,因为fooBar是一个不是对象文字的变量,因此可以包含未知属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM