簡體   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